from fastapi import FastAPI, Query, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import os

from downloader import download_song
from config import settings

os.makedirs(settings.MUSIC_DIR, exist_ok=True)
print(f"Using MUSIC_DIR: {settings.MUSIC_DIR}")

app = FastAPI(title="Tunedrop", version="1.0.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/download")
def download(query: str = Query(..., min_length=2)):
    try:
        result = download_song(query)
        return JSONResponse(content={"status": "success", **result})
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000, log_level="info", reload=True)