import pathlib
import string
import sys
from pathlib import Path

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse
from starlette.responses import JSONResponse

from backend.browser_runtime import _browser_preview_path, _browser_preview_state
from backend.config import API_AUTH_TOKEN, OUTPUT_DIR


router = APIRouter()


@router.get("/api/auth/token")
def api_auth_token(request: Request):
    """Return the bearer token for loopback-served frontend bootstrap."""
    client = request.client.host if request.client else ""
    if client not in ("127.0.0.1", "::1", "localhost"):
        raise HTTPException(status_code=403, detail="Forbidden")
    return {"token": API_AUTH_TOKEN}


@router.get("/api/browse-dirs")
def api_browse_dirs(path: str = ""):
    """List subdirectories for the directory-picker UI."""
    if not path:
        if sys.platform == "win32":
            drives = []
            for letter in string.ascii_uppercase:
                drive_path = pathlib.Path(f"{letter}:\\")
                if drive_path.exists():
                    drives.append(str(drive_path))
            return {"dirs": drives, "parent": None, "current": ""}
        path = "/"
    resolved = pathlib.Path(path).resolve()
    if not resolved.is_dir():
        return {"dirs": [], "parent": str(resolved.parent), "current": str(resolved)}
    dirs = []
    try:
        for child in sorted(resolved.iterdir()):
            if child.is_dir() and not child.name.startswith("."):
                dirs.append(child.name)
                if len(dirs) >= 200:
                    break
    except PermissionError:
        pass
    parent = str(resolved.parent) if resolved.parent != resolved else None
    return {"dirs": dirs, "parent": parent, "current": str(resolved)}


@router.get("/api/output/{filename:path}")
def api_output_file(filename: str):
    safe_name = Path(filename).name
    if not safe_name or safe_name.startswith('.'):
        raise HTTPException(status_code=400, detail="Invalid filename.")
    path = OUTPUT_DIR / safe_name
    if not path.exists() or not path.is_file():
        raise HTTPException(status_code=404, detail="File not found.")
    return FileResponse(path, filename=safe_name)


@router.get("/api/browser/state")
def api_browser_state():
    return JSONResponse(_browser_preview_state())


@router.get("/api/browser/preview")
def api_browser_preview():
    path = _browser_preview_path()
    if not path.exists() or not path.is_file():
        raise HTTPException(status_code=404, detail="Browser preview not available.")
    return FileResponse(path, media_type="image/png", filename=path.name)