"""PRD Plugin skill-usage report.

Joins the skill-usage telemetry (.prd_plugin/local/skill-usage.jsonl, captured by
the Claude Code PostToolUse hook) with the ID records (requests/tracking/
changelog/evidence/decisions, which carry created_at + agent + session) into a
timeline and a per-session summary — so you can see which skills were used, when,
and whether work shipped without the workflow skills being invoked.

Read-only. Host-agnostic: the capture is host-specific, but this report just
reads the log + state.
"""

import argparse
import json
from pathlib import Path

STATE_FILES = {
    ".prd_plugin/state/requests.json": ("requests", "REQ"),
    ".prd_plugin/state/tracking.json": ("records", "TRK"),
    ".prd_plugin/state/changelog.json": ("changes", "CHG"),
    ".prd_plugin/state/evidence.json": ("records", "EV"),
    ".prd_plugin/state/decisions.json": ("decisions", "DEC"),
}
# Skills whose absence around shipped work is worth flagging.
DISCIPLINE_SKILLS = {
    "project-verification-before-completion",
    "project-test-driven-implementation",
}


def _read_json(path):
    return json.loads(Path(path).read_text(encoding="utf-8-sig"))


def load_usage(root):
    path = Path(root) / ".prd_plugin" / "local" / "skill-usage.jsonl"
    events = []
    if path.is_file():
        for line in path.read_text(encoding="utf-8").splitlines():
            line = line.strip()
            if not line:
                continue
            try:
                events.append(json.loads(line))
            except Exception:
                continue
    return events


def load_artifacts(root):
    out = []
    for rel, (key, prefix) in STATE_FILES.items():
        path = Path(root) / rel
        if not path.is_file():
            continue
        try:
            data = _read_json(path)
        except Exception:
            continue
        for item in (data.get(key, []) if isinstance(data, dict) else []):
            if not isinstance(item, dict) or "id" not in item:
                continue
            out.append({
                "id": item["id"],
                "kind": prefix,
                "ts": item.get("created_at") or item.get("updated_at") or item.get("timestamp") or "",
                "agent": item.get("created_by_agent") or item.get("requested_by_agent") or item.get("owner_agent"),
                "session": item.get("created_from_session") or item.get("requested_from_session"),
            })
    return out


def build_report(root="."):
    root = Path(root).resolve()
    usage = load_usage(root)
    artifacts = load_artifacts(root)

    skill_counts = {}
    for e in usage:
        skill_counts[e.get("skill", "unknown")] = skill_counts.get(e.get("skill", "unknown"), 0) + 1

    by_session = {}
    for e in usage:
        s = e.get("session") or "unknown-session"
        by_session.setdefault(s, []).append(e.get("skill", "unknown"))

    timeline = sorted(
        [{"ts": e.get("ts", ""), "type": "skill", "what": e.get("skill"), "session": e.get("session")} for e in usage]
        + [{"ts": a["ts"], "type": "artifact", "what": a["id"], "session": a.get("session")} for a in artifacts if a["ts"]],
        key=lambda x: str(x["ts"]),
    )

    skills_used = set(skill_counts)
    findings = []
    shipped = [a for a in artifacts if a["kind"] in ("CHG", "EV")]
    if shipped and not (skills_used & DISCIPLINE_SKILLS):
        findings.append(
            "Work was recorded (CHG/EV) but no verification/TDD skill use is logged — "
            "either the skills were skipped or skill-usage capture is not active."
        )
    if artifacts and not usage:
        findings.append(
            "No skill-usage telemetry found at all. If this repo has done work, either "
            "the PostToolUse logger is not installed/active or no skills were invoked."
        )

    return {
        "status": "attention" if findings else "ok",
        "repo_root": str(root),
        "skill_usage_events": len(usage),
        "skill_counts": dict(sorted(skill_counts.items(), key=lambda x: -x[1])),
        "by_session": {s: sorted(set(v)) for s, v in by_session.items()},
        "artifact_count": len(artifacts),
        "timeline": timeline,
        "findings": findings,
    }


def format_markdown(r):
    lines = ["# PRD Plugin Skill-Usage Report", "", f"Status: `{r['status']}`",
             f"Skill-usage events: {r['skill_usage_events']} | artifacts: {r['artifact_count']}", "",
             "## Skills used (count)", ""]
    if not r["skill_counts"]:
        lines.append("- None logged")
    for skill, n in r["skill_counts"].items():
        lines.append(f"- {skill}: {n}")
    lines += ["", "## By session", ""]
    if not r["by_session"]:
        lines.append("- None")
    for s, skills in r["by_session"].items():
        lines.append(f"- `{s}`: {', '.join(skills)}")
    lines += ["", "## Findings", ""]
    if not r["findings"]:
        lines.append("- None")
    for f in r["findings"]:
        lines.append(f"- {f}")
    return "\n".join(lines) + "\n"


def main(argv=None):
    parser = argparse.ArgumentParser(description="Report which PRD Plugin skills were used, when, and where (read-only).")
    parser.add_argument("--repo-root", default=".")
    parser.add_argument("--format", choices=("json", "markdown"), default="markdown")
    parser.add_argument("--output")
    args = parser.parse_args(argv)
    report = build_report(args.repo_root)
    text = json.dumps(report, indent=2) if args.format == "json" else format_markdown(report)
    if args.output:
        Path(args.output).parent.mkdir(parents=True, exist_ok=True)
        Path(args.output).write_text(text, encoding="utf-8")
    print(text)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
