from fastapi import APIRouter, BackgroundTasks, HTTPException
from app.models.schemas import DownloadRequest, DownloadResponse, JobStatus
from app.models.job_store import job_store
from app.services.downloader import download_video, detect_platform

router = APIRouter()


async def download_task(job_id: str, url: str):
    """Background task for downloading video."""
    job_store.update_job(job_id, status=JobStatus.DOWNLOADING, progress=10)

    success, message, video_path = await download_video(url, job_id)

    if success:
        job_store.update_job(
            job_id,
            status=JobStatus.READY_FOR_TRIM,  # Ready for trimming step
            video_path=video_path,
            progress=30,
        )
    else:
        job_store.update_job(
            job_id,
            status=JobStatus.FAILED,
            error=message,
        )


@router.post("/", response_model=DownloadResponse)
async def start_download(
    request: DownloadRequest,
    background_tasks: BackgroundTasks
):
    """Start video download from URL."""
    platform = request.platform or detect_platform(request.url)

    # Create job
    job = job_store.create_job(original_url=request.url)

    # Start background download
    background_tasks.add_task(download_task, job.job_id, request.url)

    return DownloadResponse(
        job_id=job.job_id,
        status=JobStatus.PENDING,
        message=f"Download started for {platform} video"
    )


@router.get("/platforms")
async def get_supported_platforms():
    """Get list of supported platforms."""
    return {
        "platforms": [
            {"id": "douyin", "name": "抖音 (Douyin)", "domains": ["douyin.com", "iesdouyin.com"]},
            {"id": "kuaishou", "name": "快手 (Kuaishou)", "domains": ["kuaishou.com", "gifshow.com"]},
            {"id": "bilibili", "name": "哔哩哔哩 (Bilibili)", "domains": ["bilibili.com"]},
            {"id": "tiktok", "name": "TikTok", "domains": ["tiktok.com"]},
            {"id": "youtube", "name": "YouTube", "domains": ["youtube.com", "youtu.be"]},
        ]
    }
