"""FastAPI application for peepfilt."""

from __future__ import annotations
from pathlib import Path
from typing import Optional
from importlib.resources import files

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field

from peepfilt.config import DEFAULT_CONF, DEFAULT_BATCH_SIZE, PORT

app = FastAPI(title="peepfilt API", version="0.1.0")

# Allow simple local usage from file:// or any origin
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)


class ScanRequest(BaseModel):
    images_dir: str = Field(..., description="Directory of images to scan")
    no_people_dir: Optional[str] = Field(
        None,
        description="Directory to move images without people (default: <images_dir>/no_people)",
    )
    conf: float = Field(
        DEFAULT_CONF, ge=0.0, le=1.0, description="Confidence threshold"
    )
    batch_size: int = Field(
        DEFAULT_BATCH_SIZE, ge=1, description="Batch size for inference"
    )


@app.get("/health")
def health() -> dict:
    return {"status": "ok"}


@app.post("/scan-dir")
def scan_dir(req: ScanRequest) -> dict:
    from peepfilt.batch import scan_and_filter

    try:
        stats = scan_and_filter(
            input_dir=Path(req.images_dir),
            no_people_dir=req.no_people_dir,
            conf=req.conf,
            batch_size=req.batch_size,
        )
        return stats
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


# Serve static frontend files via packaged resources when available
frontend_path = files("peepfilt") / "frontend"
if frontend_path.is_dir():
    app.mount(
        "/", StaticFiles(directory=str(frontend_path), html=True), name="frontend"
    )


def serve_production() -> int:
    """Start the FastAPI app using uvicorn without reload."""
    import uvicorn

    uvicorn.run(
        "peepfilt.api:app",
        host="localhost",
        port=PORT,
        reload=False,
    )
    return 0
