#!/usr/bin/env python3
"""Status line and hook commands for agent sessions started by launch_sessions.py. Not run by hand.

  usage_hooks.py statusline SESSION-ID    status line: records the plan usage Claude Code passes on stdin
  usage_hooks.py limit-hit SESSION-ID     StopFailure hook (matcher rate_limit): records that the session hit a limit

The launcher writes a settings file for each session that points its status line and its StopFailure hook here
(launch_sessions.py, settings_for). Claude Code gives the status line the account's usage of its rolling windows
(`rate_limits.five_hour` and `rate_limits.seven_day`: used_percentage 0 to 100, resets_at in Unix seconds), so every
running session refreshes one shared usage file. The launcher reads that file to hold back new sessions, and reads
the limit markers to continue a session that Claude Code did not continue by itself after the reset.

Writes  <state>/usage.json and <state>/limited/<SESSION-ID>.json, where <state> is HIS_STATE or ~/.cache/his
"""
import json, os, sys, tempfile, time

STATE = os.environ.get('HIS_STATE', os.path.expanduser('~/.cache/his'))
USAGE = os.path.join(STATE, 'usage.json')
LIMITED = os.path.join(STATE, 'limited')


def put(path, value):
    """Write JSON atomically, so that a reader never sees half a file."""
    os.makedirs(os.path.dirname(path), exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix='.tmp-')
    with os.fdopen(fd, 'w') as f:
        json.dump(value, f, indent=1)
    os.replace(tmp, path)


def read(path):
    try:
        return json.load(open(path))
    except (OSError, ValueError):
        return None


def stdin_json():
    try:
        return json.loads(sys.stdin.read() or '{}')
    except ValueError:
        return {}


def statusline(sid):
    data = stdin_json()
    rl = data.get('rate_limits') or {}
    windows = {k: rl[k] for k in ('five_hour', 'seven_day') if isinstance(rl.get(k), dict)}
    if windows:
        put(USAGE, dict(captured_at=int(time.time()), session=sid, **windows))
    model = ((data.get('model') or {}).get('display_name')) or ''
    parts = [f'HIS {sid}'] + ([model] if model else [])
    for k, label in (('five_hour', '5h'), ('seven_day', '7d')):
        if k in windows and windows[k].get('used_percentage') is not None:
            w = windows[k]
            reset = time.strftime('%a %H:%M' if k == 'seven_day' else '%H:%M', time.localtime(w.get('resets_at') or 0))
            parts.append(f'{label} {w["used_percentage"]:.0f}% (resets {reset})')
    print(' · '.join(parts))


def limit_hit(sid):
    data = stdin_json()
    usage = read(USAGE) or {}
    put(os.path.join(LIMITED, f'{sid}.json'), dict(
        session=sid, at=int(time.time()), error=data.get('error', ''), details=data.get('error_details', ''),
        message=data.get('last_assistant_message', ''),
        resets={k: (usage.get(k) or {}).get('resets_at') for k in ('five_hour', 'seven_day')},
        used={k: (usage.get(k) or {}).get('used_percentage') for k in ('five_hour', 'seven_day')}))


if __name__ == '__main__':
    if len(sys.argv) != 3 or sys.argv[1] not in ('statusline', 'limit-hit'):
        sys.exit(__doc__)
    try:
        (statusline if sys.argv[1] == 'statusline' else limit_hit)(sys.argv[2])
    except Exception as e:   # a status line or hook must never break the session
        print(f'HIS {sys.argv[2]} · usage not recorded ({e.__class__.__name__})')
