#!/usr/bin/env python3
"""Statusline: model | git branch | context usage, with rollover cue at 75%+.

Also persists the official context window size to a temp state file so
context_monitor.py computes percentages against the real window instead
of a hardcoded default.
"""

import json
import os
import subprocess
import sys
import tempfile


def persist_window_size(data: dict) -> None:
    size = (data.get("context_window") or {}).get("context_window_size")
    if not size:
        return
    tmp = tempfile.gettempdir()
    names = ["claude_ctxwin_global"]
    session = data.get("session_id")
    if session:
        names.append(f"claude_ctxwin_{session}")
    for name in names:
        try:
            with open(os.path.join(tmp, name), "w") as f:
                f.write(str(int(size)))
        except OSError:
            pass


def main() -> None:
    data = json.load(sys.stdin)
    persist_window_size(data)
    parts = [(data.get("model") or {}).get("display_name", "?")]

    cwd = (data.get("workspace") or {}).get("current_dir") or "."
    try:
        branch = subprocess.run(
            ["git", "branch", "--show-current"],
            capture_output=True, text=True, timeout=2, cwd=cwd,
        ).stdout.strip()
        if branch:
            parts.append(f"branch {branch}")
    except Exception:
        pass

    pct = (data.get("context_window") or {}).get("used_percentage")
    if pct is not None:
        pct = round(pct)
        color = "\033[31m" if pct >= 75 else "\033[33m" if pct >= 50 else "\033[32m"
        cue = " -> /handoff" if pct >= 75 else ""
        parts.append(f"{color}ctx {pct}%{cue}\033[0m")

    print(" | ".join(parts))


if __name__ == "__main__":
    try:
        main()
    except Exception:
        print("statusline error")
    sys.exit(0)
