#!/usr/bin/env python3
"""
FlyDocs Hook: session-end.py
Triggered: When a Claude Code session ends (SessionEnd)
Purpose: Start the automatic session record for the thread (FLY-1774, SL-3),
         detached, and return at once. Budget: 1.5 s in all.

The record itself is `session.py auto-record`: local facts only, no model call,
a noise gate, a claim file against double posts, bounded to 20 s. This hook
only decides whether to start it. It never waits for it, writes nothing and
prints nothing; every error is swallowed, because an ending session has nobody
to read one.

Exit codes:
  0 - always
"""

import json
import os
import sys
from pathlib import Path

SCRIPT_DIR = Path(__file__).parent.resolve()
SESSION_SCRIPT = (SCRIPT_DIR.parent / 'skills' / 'flydocs-workflow' / 'scripts'
                  / 'session.py')


def main() -> None:
    try:
        input_data = json.loads(sys.stdin.read())
    except (json.JSONDecodeError, ValueError):
        input_data = {}
    if not isinstance(input_data, dict):
        return

    from repo_context import (
        harness_arg, is_cursor_running_claude_hook, resolve_repo_dir,
        resolve_session_dir, thread_key, thread_state,
    )
    # Claude Code only (Codex, Cursor and OpenCode are SL-3b). A harness flag
    # means another harness wired this file; Cursor also runs Claude's hooks.
    if harness_arg() is not None or is_cursor_running_claude_hook(input_data):
        return
    key = thread_key(input_data)
    if key is None or thread_state is None or key.harness != 'claude':
        return

    cwd = input_data.get('cwd') or os.environ.get('CLAUDE_PROJECT_DIR', '')
    if cwd and Path(cwd).is_dir():
        os.chdir(cwd)
    session_dir = resolve_session_dir(resolve_repo_dir())

    # The cheap checks, so a session that cannot produce a record does not
    # start a Python process to find that out. The command repeats them under
    # its claim.
    thread = thread_state.read_thread(session_dir, key) or {}
    if thread.get('startedAt') is None \
            or thread.get('wrappedAt') is not None \
            or thread.get('autoRecordedAt') is not None:
        return
    if thread_state.is_child_thread(thread, input_data, os.environ):
        return

    import auto_record
    auto_record.spawn_auto_record(
        SESSION_SCRIPT, key.harness, key.session_key, 'hook:SessionEnd',
        os.getcwd())


if __name__ == '__main__':
    try:
        main()
    except BaseException:  # noqa: BLE001 - an ending session reads no errors
        pass
    sys.exit(0)
