from __future__ import annotations

from pathlib import Path

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import FileResponse
from sqlite3 import Connection

from jarvis_finance.api.dependencies import get_db
from jarvis_finance.api.schemas.reports import ReportMetadata
from jarvis_finance.config.settings import find_repo_root, load_settings
from jarvis_finance.services.finance_command_center import generate_monthly_report
from jarvis_finance.services.report_service import list_runtime_reports
from jarvis_finance.services.reports_v1 import generate_report_v1, list_reports_v1, preview_report_v1

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


@router.post("/reports/preview")
def report_preview(payload: dict, conn: Connection = Depends(get_db)) -> dict:
    try:
        return preview_report_v1(conn, report_type=str(payload.get("report_type") or "budget_monthly"), period=str(payload.get("period") or payload.get("month") or "2026-05"))
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post("/reports/generate")
def report_generate(payload: dict, conn: Connection = Depends(get_db)) -> dict:
    try:
        return generate_report_v1(conn, report_type=str(payload.get("report_type") or "budget_monthly"), period=str(payload.get("period") or payload.get("month") or "2026-05"), format=str(payload.get("format") or "html"))
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post("/reports/monthly")
def monthly_report(payload: dict | None = None, conn: Connection = Depends(get_db)) -> dict:
    try:
        return generate_report_v1(conn, report_type="budget_monthly", period=(payload or {}).get("month") or "2026-05", format=(payload or {}).get("format") or "markdown")
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.get("/reports")
def reports() -> list[dict]:
    return list_reports_v1()


@router.get("/reports/files/{report_path:path}")
def report_file(report_path: str):
    settings = load_settings(repo_root=find_repo_root())
    base = settings.runtime_paths.reports_dir.resolve()
    path = (base / report_path).resolve()
    if base not in path.parents or not path.exists() or path.suffix.lower() not in {".html", ".md", ".pdf"}:
        raise HTTPException(status_code=404, detail="report_not_found")
    media = "text/html" if path.suffix.lower() == ".html" else "text/markdown" if path.suffix.lower() == ".md" else "application/pdf"
    return FileResponse(path, media_type=media, filename=path.name)
