#!/usr/bin/env python
"""PRD Plugin drift-check Stop hook for Claude Code (REQ-065).

Observation-only. When drift.monitoring.on_stop is enabled, this runs the cheap
on-stop validator set (tracking + docs + traceability drift) via drift_monitor and
surfaces a one-line summary into context, so drift is seen rather than left in
silent JSONL. It NEVER blocks the stop and NEVER fails: any error resolves to a
quiet exit 0. Toggle with /prd-drift or drift.monitoring.on_stop in config.

Default off — no cost unless turned on.
"""

import sys


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

        root = Path.cwd()
        # locate drift_monitor: repo-local .prd_plugin/scripts or hub scripts/
        for rel in (Path(".prd_plugin") / "scripts", Path("scripts")):
            cand = root / rel
            if (cand / "drift_monitor.py").is_file():
                sys.path.insert(0, str(cand))
                break
        else:
            return 0  # monitor not installed — nothing to do

        import drift_monitor

        result = drift_monitor.stop_check(root)
        if not result.get("ran"):
            return 0
        total = result.get("total", 0)
        line = result.get("summary", "")
        if total:
            print(f"[PRD Plugin] drift check: {line}")
        # silent when clean; the point is to surface drift, not chatter
    except Exception:
        pass  # fail-open: a drift check must never break a stop
    return 0


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