"""Export routes."""

from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from app.core.db import get_db
from app.schemas.export import ExportReportRead
from app.schemas.report import ReportExportRead, ReportExportRequest
from app.services import report_generator

router = APIRouter(tags=["report"])


@router.post("/report/export", response_model=ReportExportRead)
def export_report(
    engagement_id: int | None = Query(default=None, ge=1),
    include_ai: bool | None = Query(default=None),
    payload: ReportExportRequest | None = Body(default=None),
    db: Session = Depends(get_db),
) -> ReportExportRead:
    """Generate an AI-enhanced markdown report for one engagement."""
    selected_engagement_id = payload.engagement_id if payload and payload.engagement_id is not None else engagement_id
    include_vault = bool(payload.include_vault) if payload else False
    selected_include_ai = payload.include_ai if payload and payload.include_ai is not None else include_ai
    vault_query = payload.vault_query if payload else None

    if selected_engagement_id is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="engagement_id is required",
        )

    try:
        report_payload = report_generator.generate_report_payload(
            db=db,
            engagement_id=selected_engagement_id,
            include_vault=include_vault,
            include_ai=selected_include_ai,
            vault_query=vault_query,
        )
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc

    return ReportExportRead.model_validate(report_payload)


@router.post("/export/report", response_model=ExportReportRead, deprecated=True)
def export_report_legacy(
    engagement_id: int | None = Query(default=None, ge=1),
    include_ai: bool | None = Query(default=None),
    payload: ReportExportRequest | None = Body(default=None),
    db: Session = Depends(get_db),
) -> ExportReportRead:
    """Legacy file export endpoint kept for backward compatibility."""
    selected_engagement_id = payload.engagement_id if payload and payload.engagement_id is not None else engagement_id
    include_vault = bool(payload.include_vault) if payload else False
    selected_include_ai = payload.include_ai if payload and payload.include_ai is not None else include_ai
    vault_query = payload.vault_query if payload else None

    if selected_engagement_id is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="engagement_id is required",
        )

    try:
        path = report_generator.generate_report(
            db=db,
            engagement_id=selected_engagement_id,
            include_vault=include_vault,
            include_ai=selected_include_ai,
            vault_query=vault_query,
        )
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc

    return ExportReportRead(status="generated", path=path)
