#!/usr/bin/env node
// Remind about current config-audit session phase on session end
// Returns JSON: {} if no active session, systemMessage if active

import { readdirSync, readFileSync, statSync, existsSync } from 'fs';
import { join, basename, dirname } from 'path';
import { homedir } from 'os';

const sessionsDir = join(homedir(), '.config-audit', 'sessions');

if (!existsSync(sessionsDir)) {
  console.log('{}');
  process.exit(0);
}

function parseYamlValue(content, key) {
  const match = content.match(new RegExp(`${key}:\\s*"?([^"\\n]*)"?`));
  return match ? match[1].trim() : '';
}

let latestState = '';
let latestTime = 0;

try {
  const entries = readdirSync(sessionsDir, { withFileTypes: true });

  for (const entry of entries) {
    if (!entry.isDirectory()) continue;

    const stateFile = join(sessionsDir, entry.name, 'state.yaml');
    if (!existsSync(stateFile)) continue;

    const fileTime = statSync(stateFile).mtimeMs;
    if (fileTime > latestTime) {
      latestTime = fileTime;
      latestState = stateFile;
    }
  }
} catch {
  console.log('{}');
  process.exit(0);
}

if (latestState) {
  // Only remind if session was touched in the last 2 hours (active work)
  const twoHoursMs = 2 * 60 * 60 * 1000;
  if (Date.now() - latestTime > twoHoursMs) {
    console.log('{}');
    process.exit(0);
  }

  const content = readFileSync(latestState, 'utf-8');
  const currentPhase = parseYamlValue(content, 'current_phase');
  const nextPhase = parseYamlValue(content, 'next_phase');

  if (currentPhase && currentPhase !== 'verify' && currentPhase !== 'complete') {
    const sessionId = basename(dirname(latestState));
    console.log(JSON.stringify({
      systemMessage: `config-audit: Session ${sessionId} is at phase '${currentPhase}'. Next: /config-audit ${nextPhase}`
    }));
    process.exit(0);
  }
}

console.log('{}');
process.exit(0);
