from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

from jarvis_finance.api.schemas.reports import ReportMetadata
from jarvis_finance.config.settings import find_repo_root, load_settings

REPORT_EXTENSIONS = {".html", ".htm", ".pdf", ".md", ".json"}


def _report_type(path: Path) -> str:
    stem = path.stem.lower()
    if "crypto" in stem:
        return "crypto"
    if "portfolio" in stem:
        return "portfolio"
    if "cash" in stem:
        return "cash"
    return "report"


def list_runtime_reports() -> list[ReportMetadata]:
    settings = load_settings(repo_root=find_repo_root())
    reports_dir = settings.runtime_paths.reports_dir
    if not reports_dir.exists():
        return []
    reports: list[ReportMetadata] = []
    for path in sorted((p for p in reports_dir.rglob("*") if p.is_file() and p.suffix.lower() in REPORT_EXTENSIONS), key=lambda p: p.stat().st_mtime, reverse=True)[:50]:
        stat = path.stat()
        rel = path.relative_to(reports_dir)
        reports.append(
            ReportMetadata(
                report_id=str(rel),
                report_type=_report_type(path),
                title=path.stem.replace("_", " ").replace("-", " ").title(),
                format=path.suffix.lower().lstrip("."),
                generated_at=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat(),
                data_quality_status="ok",
                path_display=str(path),
            )
        )
    return reports
