"""Read-only staleness auditor.

Flags PRD Plugin records that have gone stale by the thresholds in
`.prd_plugin/config.json`, so the manual "check whether this record is stale"
step in many skills becomes one command. Reports only; never mutates state.
"""

import argparse
import json
import sys
from datetime import datetime, timezone
from pathlib import Path


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


def _load(root, rel):
    path = Path(root) / rel
    if path.is_file():
        try:
            return _read_json(path)
        except Exception:
            return None
    return None


def _parse_time(value):
    if not value or not isinstance(value, str):
        return None
    text = value.strip()
    if text.endswith("Z"):
        text = text[:-1] + "+00:00"
    for parse in (
        lambda t: datetime.fromisoformat(t),
        lambda t: datetime.strptime(t, "%Y-%m-%d"),
    ):
        try:
            dt = parse(text)
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            return dt
        except ValueError:
            continue
    return None


def _last_activity(record):
    for key in ("updated_at", "last_seen_at", "created_at", "date", "reviewed_at"):
        dt = _parse_time(record.get(key))
        if dt is not None:
            return dt
    return None


def _age_days(record, now):
    dt = _last_activity(record)
    if dt is None:
        return None
    return (now - dt).days


def _config(root):
    cfg = _load(root, ".prd_plugin/config.json") or {}
    return cfg if isinstance(cfg, dict) else {}


def audit(root=".", now_text=None):
    root = Path(root).resolve()
    now = _parse_time(now_text) if now_text else datetime.now(timezone.utc)
    cfg = _config(root)
    req_stale = (cfg.get("requests") or {}).get("stale_after_days", 14)
    accepted_stale = (cfg.get("health") or {}).get("accepted_request_stale_after_days", 7)
    trk_stale = (cfg.get("health") or {}).get("stale_tracking_after_days", 14)

    stale = []

    requests = _load(root, ".prd_plugin/state/requests.json") or {}
    for r in requests.get("requests", []) if isinstance(requests, dict) else []:
        if not isinstance(r, dict):
            continue
        status = r.get("status")
        age = _age_days(r, now)
        if age is None:
            continue
        if status in ("proposed", "in_review", "needs_info") and age > req_stale:
            stale.append({"id": r.get("id"), "kind": "request", "status": status,
                          "age_days": age, "threshold": req_stale})
        elif status == "accepted" and not r.get("graduated_to") and age > accepted_stale:
            stale.append({"id": r.get("id"), "kind": "request", "status": "accepted_ungraduated",
                          "age_days": age, "threshold": accepted_stale})

    tracking = _load(root, ".prd_plugin/state/tracking.json") or {}
    for t in tracking.get("records", []) if isinstance(tracking, dict) else []:
        if not isinstance(t, dict):
            continue
        if t.get("status") in ("active", "in_progress"):
            age = _age_days(t, now)
            if age is not None and age > trk_stale:
                stale.append({"id": t.get("id"), "kind": "tracking", "status": t.get("status"),
                              "age_days": age, "threshold": trk_stale})

    health = _load(root, ".prd_plugin/state/health.json") or {}
    for h in health.get("findings", []) if isinstance(health, dict) else []:
        if not isinstance(h, dict):
            continue
        if h.get("status") in ("open", "blocked"):
            age = _age_days(h, now)
            if age is not None and age > trk_stale:
                stale.append({"id": h.get("id"), "kind": "health", "status": h.get("status"),
                              "age_days": age, "threshold": trk_stale})

    return {
        "status": "attention" if stale else "ok",
        "repo_root": str(root),
        "counts": {"stale": len(stale)},
        "stale": stale,
    }


def format_markdown(report):
    lines = ["# PRD Plugin Staleness Audit", "", f"Status: `{report['status']}`", "",
             f"Stale records: {report['counts']['stale']}", "", "## Stale", ""]
    if not report["stale"]:
        lines.append("- None")
    for s in report["stale"]:
        lines.append(f"- `{s['id']}` ({s['kind']}/{s['status']}): {s['age_days']}d old "
                     f"(threshold {s['threshold']}d)")
    return "\n".join(lines) + "\n"


def main(argv=None):
    parser = argparse.ArgumentParser(description="Flag stale PRD Plugin records by config thresholds (read-only).")
    parser.add_argument("--repo-root", default=".")
    parser.add_argument("--now", default=None, help="ISO timestamp for deterministic audits.")
    parser.add_argument("--format", choices=("json", "markdown"), default="markdown")
    parser.add_argument("--output")
    args = parser.parse_args(argv)
    report = audit(args.repo_root, args.now)
    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())
