#!/usr/bin/env node
// SessionStart hook — re-inject "advisor is dead this session" after a context reset.
//
// Problem (distinct from the skill's spawn-vs-continue sidecar): when the user has
// told the agent advisor is API-dead and to use /dead-advisor, that fact lives only
// in the live context. A /compact or --resume wipes it; the agent then silently
// reverts to calling the real (still-broken) advisor.
//
// Signal = the sidecar the /dead-advisor skill writes: ~/.claude/dead-advisor-state/
// <session>.id exists iff a dead-advisor subagent was spawned this session (i.e. the
// user already declared advisor dead). This hook re-derives that fact from disk and
// reminds the agent — non-absolute, since advisor may have recovered.
//
// Fail-closed + read-only: any unexpected state → exit 0 silently, mutate nothing.

import { readFileSync, existsSync } from 'node:fs';
import { join, basename } from 'node:path';

function readStdin() { try { return readFileSync(0, 'utf8'); } catch { return ''; } }
let payload = {};
try { payload = JSON.parse(readStdin() || '{}'); } catch { payload = {}; }

// Only the events that drop live context. Unknown/absent source → do nothing.
const source = String(payload.source || '');
if (source !== 'compact' && source !== 'resume') process.exit(0);

// Session id: explicit field, else derive from transcript filename.
let session = String(payload.session_id || '');
if (!session && payload.transcript_path) {
  session = basename(String(payload.transcript_path)).replace(/\.jsonl$/, '');
}
if (!session) process.exit(0);

const idFile = join(process.env.HOME || '', '.claude', 'dead-advisor-state', `${session}.id`);
if (!existsSync(idFile)) process.exit(0);

let agentId = '';
try { agentId = (readFileSync(idFile, 'utf8').split('\n')[0] || '').trim(); } catch { process.exit(0); }

const ctx = [
  `[dead-advisor] This session earlier hit advisor API failures and spun up a reusable`,
  `dead-advisor subagent${agentId ? ` (agentId ${agentId})` : ''}. That fact predates this ${source} and may have`,
  `dropped from your live context.`,
  '',
  'If you are about to consult advisor and it is STILL failing, do NOT keep retrying the dead',
  'tool — run /dead-advisor. The skill checks the on-disk sidecar and reuses the existing',
  'subagent (it does not spawn a duplicate). If advisor has recovered, use it normally; this',
  'is a reminder, not a block.',
].join('\n');

process.stdout.write(JSON.stringify({
  hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: ctx },
}));
process.exit(0);
