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 OccupationService:
    """Produces a preliminary occupation-alignment support analysis."""

    def analyze(self, applicant_base: Path) -> dict[str, Any]:
        applicant = read_json(applicant_base / "applicant.json", default={}) or {}
        nominated = applicant.get("nominated_occupation", "")

        evidence_keywords: list[str] = []
        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 {}
            evidence_keywords.extend(payload.get("entities", {}).get("detected_keywords", []))

        unique_keywords = sorted(set(evidence_keywords))

        output = {
            "generated_at": now_iso(),
            "nominated_occupation": nominated,
            "verified_evidence": [],
            "inferred_suggestions": [
                f"Map responsibilities from verified employment records to occupation '{nominated or 'TBD'}'.",
                "Cross-check duties against official occupation criteria with a migration professional.",
            ],
            "missing_evidence": [
                "Detailed duty statements tied to each role period.",
                "Employer references with role, dates, and hours.",
            ],
            "detected_keywords": unique_keywords,
            "disclaimer": "Support workflow only; not legal advice and not a visa decision.",
        }

        generated_dir = applicant_base / "generated"
        write_json(generated_dir / "occupation_analysis.json", output)

        md_lines = [
            "# Occupation Analysis",
            "",
            "Support workflow only; not legal advice and not a visa decision.",
            "",
            f"## Nominated Occupation\n- {nominated or 'Not set'}",
            "",
            "## Verified Evidence",
            "- None auto-verified in V1.",
            "",
            "## Inferred Suggestions",
            "- Map employment records to occupation duties and required skill level.",
            "- Validate with migration professional before submission.",
            "",
            "## Missing Evidence",
            "- Employer references confirming role/dates/hours.",
            "- Duty statements that align to nominated occupation.",
            "",
            f"## Detected Keywords\n- {', '.join(unique_keywords) if unique_keywords else 'None'}",
        ]
        (generated_dir / "occupation_analysis.md").write_text("\n".join(md_lines) + "\n", encoding="utf-8")
        return output
