#!/usr/bin/env python3
"""
FlyDocs Hook: usage-capture.py (FLY-1013)
Triggered: When the agent finishes a response (Stop)
Purpose: Fire-and-forget AI usage counter capture via `flydocs usage report`

Thin shim only — all parsing, consent gating, and reporting live in the CLI.
The CLI silently no-ops unless the workspace has usage collection enabled
and the user hasn't opted out. Counters only, never message content.

Exit codes:
  0 - Always (must never block or slow a session)
"""

import json
import subprocess
import sys


def main() -> None:
    try:
        input_data = json.loads(sys.stdin.read())
    except (json.JSONDecodeError, ValueError):
        sys.exit(0)

    transcript_path = input_data.get('transcript_path')
    session_id = input_data.get('session_id')
    if not transcript_path:
        sys.exit(0)

    cmd = ['flydocs', 'usage', 'report', '--transcript', str(transcript_path)]
    if session_id:
        cmd += ['--session-id', str(session_id)]

    try:
        # Detached, no wait, output suppressed — capture must never delay
        # the Stop hook or surface errors into the session.
        subprocess.Popen(
            cmd,
            stdin=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            start_new_session=True,
        )
    except Exception:
        pass

    sys.exit(0)


if __name__ == '__main__':
    main()
