from fastapi import UploadFile, File
import os
from datetime import datetime

UPLOAD_DIR = "storage/uploads"

@app.post("/upload-chart/")
async def upload_chart(user_id: int, file: UploadFile = File(...)):
    # Create user directory if not exists
    user_dir = os.path.join(UPLOAD_DIR, str(user_id))
    os.makedirs(user_dir, exist_ok=True)
    
    # Generate unique filename
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    file_ext = file.filename.split('.')[-1]
    filename = f"chart_{timestamp}.{file_ext}"
    file_path = os.path.join(user_dir, filename)
    
    # Save file
    with open(file_path, "wb") as buffer:
        buffer.write(await file.read())
    
    # Store file path in database
    # (Assuming you have a database session 'db')
    db.execute(
        "INSERT INTO chart_images (user_id, file_path, uploaded_at) VALUES (:user_id, :file_path, NOW())",
        {"user_id": user_id, "file_path": file_path}
    )
    db.commit()
    
    return {"filename": filename, "path": file_path}