"""REST endpoints for the Comply CI/CD Compliance Gate."""
from __future__ import annotations

from typing import Optional

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

gate_router = APIRouter(prefix="/gate", tags=["gate"])


class GateRequest(BaseModel):
    repo_path: str
    framework: str = "eu_ai_act"
    scan_depth: str = "content"
    max_files: int = 500
    threshold_score: float = 0.0
    fail_on_regression: bool = False
    max_critical_gaps: int = -1
    use_cache: bool = False


@gate_router.post("")
def run_gate(req: GateRequest):
    """Run a compliance gate check. Returns structured pass/fail decision.

    Synchronous — blocks while scanning. Typical scan takes 5-15 seconds.
    """
    from comply.gate import run_gate as _run_gate

    try:
        result = _run_gate(
            repo_path=req.repo_path,
            framework=req.framework,
            scan_depth=req.scan_depth,
            max_files=req.max_files,
            threshold_score=req.threshold_score,
            fail_on_regression=req.fail_on_regression,
            max_critical_gaps=req.max_critical_gaps,
            use_cache=req.use_cache,
        )
        return result
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc))


@gate_router.get("/decisions")
def list_decisions(
    repo: Optional[str] = None,
    framework: Optional[str] = None,
    limit: int = 50,
):
    """List past gate decisions with optional filters."""
    from comply.store import list_gate_decisions
    return list_gate_decisions(repo=repo, framework=framework, limit=limit)


@gate_router.get("/summary")
def gate_summary(
    repo: Optional[str] = None,
    framework: Optional[str] = None,
):
    """Aggregate gate decision statistics: total, passed, failed, pass rate."""
    from comply.store import get_gate_summary
    return get_gate_summary(repo=repo, framework=framework)


@gate_router.get("/{decision_id}")
def get_decision(decision_id: str):
    """Get a single gate decision by ID."""
    from comply.store import get_gate_decision

    d = get_gate_decision(decision_id)
    if d is None:
        raise HTTPException(status_code=404, detail="Gate decision not found")
    return d
