from __future__ import annotations

from pathlib import Path
from typing import Any

from ..utils.json_utils import read_json, write_json
from ..utils.time_utils import now_iso


class TimelineService:
    """Generates a timeline summary from processed evidence artifacts."""

    def build_timeline(self, applicant_base: Path) -> dict[str, Any]:
        events: list[dict[str, Any]] = []

        for manifest_path in sorted(applicant_base.rglob("meta/manifest.json")):
            manifest = read_json(manifest_path, default={}) or {}
            status = str(manifest.get("status") or "").lower()
            if status in {"duplicate", "ignored", "archived"}:
                continue

            entities_path = manifest_path.parents[1] / "extracted" / "entities.json"
            if not entities_path.exists():
                continue
            payload = read_json(entities_path, default={}) or {}
            doc_id = payload.get("doc_id")
            category = payload.get("category")
            keywords = payload.get("entities", {}).get("detected_keywords", [])
            events.append(
                {
                    "date": None,
                    "label": f"Document processed: {doc_id}",
                    "category": category,
                    "source_keywords": keywords,
                }
            )

        timeline_json = {
            "generated_at": now_iso(),
            "events": events,
            "gap_flags": [
                "No date normalization implemented yet.",
                "Manual validation required for chronology completeness.",
            ],
        }

        generated_dir = applicant_base / "generated"
        write_json(generated_dir / "timeline.json", timeline_json)

        md_lines = [
            "# Applicant Timeline",
            "",
            "This output is workflow support only. It does not determine visa approval.",
            "",
            "## Events",
        ]
        if events:
            for event in events:
                md_lines.append(f"- {event['label']} [{event['category']}]")
        else:
            md_lines.append("- No processed documents found.")

        md_lines.extend(
            [
                "",
                "## Gap Flags",
                "- No date normalization implemented yet.",
                "- Manual validation required for chronology completeness.",
            ]
        )
        (generated_dir / "timeline.md").write_text("\n".join(md_lines) + "\n", encoding="utf-8")
        return timeline_json
