#!/usr/bin/env python
"""PRD Plugin skill-usage logger for Claude Code.

Wired to PostToolUse in .claude/settings.json. Claude Code passes the tool event
as JSON on stdin; when the Skill tool is invoked, this appends one record to
.prd_plugin/local/skill-usage.jsonl (gitignored runtime telemetry) so we can
later see which skills were used, when, and in which session — the trail the ID
records do NOT capture (invoking a skill creates no ID).

Must never block or fail a tool call: it filters cheaply and always exits 0.
"""

import sys


def main():
    try:
        import json
        from datetime import datetime, timezone
        from pathlib import Path

        raw = sys.stdin.read()
        if not raw.strip():
            return
        data = json.loads(raw)
        if not isinstance(data, dict):
            return

        tool = data.get("tool_name") or data.get("toolName") or ""
        if tool != "Skill":
            return  # only log skill invocations

        ti = data.get("tool_input") or data.get("toolInput") or {}
        if not isinstance(ti, dict):
            ti = {}
        skill = (ti.get("skill") or ti.get("name") or ti.get("command")
                 or ti.get("skill_name") or "unknown")

        cwd = data.get("cwd") or data.get("workingDirectory") or "."
        record = {
            "ts": datetime.now(timezone.utc).isoformat(),
            "skill": skill,
            "session": data.get("session_id") or data.get("sessionId"),
            "event": "skill_invoked",
        }
        log_dir = Path(cwd) / ".prd_plugin" / "local"
        log_dir.mkdir(parents=True, exist_ok=True)
        with open(log_dir / "skill-usage.jsonl", "a", encoding="utf-8") as f:
            f.write(json.dumps(record) + "\n")
    except Exception:
        # Observability must never break the session.
        pass


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