#!/usr/bin/env python
"""PRD Plugin auto-report hook for Claude Code.

Wired to Stop in .claude/settings.json. Regenerates the skill-usage report to
.prd_plugin/local/skill-usage-report.md at the end of each turn, so you never run
a script to see it — just open the file. Kept to the fast report only (it reads a
small JSONL + state JSON); heavier validators stay in CI / the commit gate.

Must never block or fail: it resolves what it can and always exits 0.
"""

import sys


def main():
    try:
        import json
        from pathlib import Path

        cwd = Path.cwd()
        raw = sys.stdin.read()
        if raw.strip():
            try:
                data = json.loads(raw)
                if isinstance(data, dict) and data.get("cwd"):
                    cwd = Path(data["cwd"])
            except Exception:
                pass

        config = {}
        try:
            config = json.loads((cwd / ".prd_plugin" / "config.json").read_text(
                encoding="utf-8-sig"))
        except Exception:
            pass
        hooks = config.get("hooks", {}) if isinstance(config, dict) else {}
        session_hook = hooks.get("session_report", {}) if isinstance(hooks, dict) else {}
        skill_report_enabled = (
            not isinstance(session_hook, dict)
            or session_hook.get("skill_usage_report", True) is True
        )

        # Locate the installed/hub script surface once for all report actions.
        scripts_dir = None
        for cand in (cwd / ".prd_plugin" / "scripts", cwd / "scripts"):
            if any((cand / name).is_file() for name in (
                    "skill_usage_report.py", "prd_graph.py", "prd_version_check.py")):
                scripts_dir = cand
                break
        if scripts_dir is None:
            return
        sys.path.insert(0, str(scripts_dir))

        if skill_report_enabled and (scripts_dir / "skill_usage_report.py").is_file():
            import skill_usage_report
            report = skill_usage_report.build_report(str(cwd))
            out = cwd / ".prd_plugin" / "local" / "skill-usage-report.md"
            out.parent.mkdir(parents=True, exist_ok=True)
            out.write_text(skill_usage_report.format_markdown(report), encoding="utf-8")

        # Optional: regenerate the traceability graph when auto-refresh is on.
        if (scripts_dir / "prd_graph.py").is_file():
            try:
                import prd_graph
                if prd_graph.auto_refresh_enabled(str(cwd)):
                    graph = prd_graph.build_graph(str(cwd))
                    gout = cwd / ".prd_plugin" / "local" / "traceability-graph.json"
                    gout.write_text(json.dumps(graph, indent=2, ensure_ascii=False) + "\n",
                                    encoding="utf-8")
            except Exception:
                pass

        # Refresh the plugin-version-available cache (TTL-gated, so npm is queried
        # at most once per ttl_hours; the nudge reads this cache next session).
        # Fail-open — a network hiccup must never break the stop. REQ-068.
        if (scripts_dir / "prd_version_check.py").is_file():
            try:
                import prd_version_check
                prd_version_check.check(str(cwd))
            except Exception:
                pass
    except Exception:
        # Auto-reporting must never break the session.
        pass


if __name__ == "__main__":
    main()
    sys.exit(0)
