from fastapi import FastAPI, Query, HTTPException
from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
import os
from downloader import download_song
from config import settings
from utils.song_list import add_song_to_list, get_song_list

app = FastAPI(
    title="Tunedrop",
    description="🎵 Search and download songs using yt-dlp. Automatically updates Navidrome library.",
    version="1.0.0"
)

# Serve /songs/filename.mp3
app.mount("/songs", StaticFiles(directory=settings.MUSIC_DIR), name="songs")

@app.get("/download")
def download(query: str = Query(..., description="Song name or YouTube search term")):
    try:
        result = download_song(query)
        if result["downloaded_files"]:
            saved_path = os.path.join(settings.MUSIC_DIR, result["downloaded_files"][0])
            add_song_to_list(saved_path, query)
        return JSONResponse(content=result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/songs")
def list_songs():
    try:
        return get_song_list()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/music/{filename}")
def serve_song(filename: str):
    file_path = os.path.join(settings.MUSIC_DIR, filename)
    if not os.path.isfile(file_path):
        raise HTTPException(status_code=404, detail="File not found")
    return FileResponse(file_path, media_type="audio/mpeg")

if __name__ == "__main__":
    uvicorn.run("main:app", host=settings.host, port=settings.port, reload=settings.reload)
