from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from pathlib import Path
import os

router = APIRouter(prefix="/api/download", tags=["Downloads"])

# Package directory
PACKAGE_DIR = Path("/app/cpanel_deployment")

@router.get("/package/{format}")
async def download_package(format: str):
    """
    Download the cPanel deployment package
    Formats: tar.gz or zip
    """
    # Find the package file
    if format == "tar.gz":
        pattern = "epic-travel-cpanel-*.tar.gz"
    elif format == "zip":
        pattern = "epic-travel-cpanel-*.zip"
    else:
        raise HTTPException(status_code=400, detail="Invalid format. Use 'tar.gz' or 'zip'")
    
    # Find the latest package
    import glob
    files = glob.glob(str(PACKAGE_DIR / pattern))
    
    if not files:
        raise HTTPException(status_code=404, detail="Package not found")
    
    # Get the most recent file
    latest_file = max(files, key=os.path.getctime)
    file_path = Path(latest_file)
    
    if not file_path.exists():
        raise HTTPException(status_code=404, detail="Package file not found")
    
    # Determine media type
    media_type = "application/gzip" if format == "tar.gz" else "application/zip"
    
    return FileResponse(
        path=str(file_path),
        media_type=media_type,
        filename=file_path.name,
        headers={
            "Content-Disposition": f"attachment; filename={file_path.name}"
        }
    )

@router.get("/list")
async def list_packages():
    """
    List available deployment packages
    """
    import glob
    
    packages = []
    
    # Find all package files
    for pattern in ["*.tar.gz", "*.zip"]:
        files = glob.glob(str(PACKAGE_DIR / pattern))
        for file_path in files:
            file_stat = os.stat(file_path)
            packages.append({
                "filename": Path(file_path).name,
                "size": f"{file_stat.st_size / 1024:.0f} KB",
                "format": "tar.gz" if file_path.endswith(".tar.gz") else "zip",
                "download_url": f"/api/download/package/{'tar.gz' if file_path.endswith('.tar.gz') else 'zip'}"
            })
    
    return {
        "packages": packages,
        "total": len(packages)
    }
