#!/usr/bin/env node
// statusline-monitor.mjs — graceful-handoff v2.0
// statusLine hook: prints a context-percent hint, never runs git.
//
// Reads JSON from stdin (Claude Code statusLine payload). If
// context_window.used_percentage is available:
//   < 60%   → no output
//   60-69%  → "kontekst NN% — vurder /graceful-handoff"
//   ≥ 70%   → "kontekst NN% — kjør /graceful-handoff NÅ"
//
// Exit 0 always. statusLine is display-only — never run git here
// (research/03 — statusLine scripts can be cancelled mid-flight).

import { readFileSync } from 'node:fs';

function readStdin() {
  try {
    return readFileSync(0, 'utf-8');
  } catch {
    return '';
  }
}

function main() {
  const raw = readStdin();
  if (!raw.trim()) {
    process.exit(0);
  }
  let payload;
  try {
    payload = JSON.parse(raw);
  } catch {
    process.exit(0);
  }

  const ctx = payload?.context_window;
  const pct = ctx?.used_percentage;
  if (typeof pct !== 'number' || isNaN(pct)) {
    process.exit(0);
  }

  if (pct >= 70) {
    process.stdout.write(`kontekst ${Math.round(pct)}% — kjør /graceful-handoff NÅ`);
  } else if (pct >= 60) {
    process.stdout.write(`kontekst ${Math.round(pct)}% — vurder /graceful-handoff`);
  }
  // < 60 → no output (silent)
  process.exit(0);
}

main();
