#!/usr/bin/env node
// Check for active (incomplete) config-audit sessions on session start
// Non-blocking: always exits 0

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

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

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

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

const activeSessions = [];

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 content = readFileSync(stateFile, 'utf-8');
    const currentPhase = parseYamlValue(content, 'current_phase');

    if (currentPhase && currentPhase !== 'verify' && currentPhase !== 'complete') {
      const nextPhase = parseYamlValue(content, 'next_phase');
      activeSessions.push({
        id: entry.name,
        phase: currentPhase,
        next: nextPhase,
      });
    }
  }
} catch {
  process.exit(0);
}

if (activeSessions.length > 0) {
  console.log(`config-audit: ${activeSessions.length} active session(s) found:`);
  let lastNext = '';
  for (const s of activeSessions) {
    console.log(`  - Session ${s.id}: phase=${s.phase}, next=${s.next}`);
    lastNext = s.next;
  }
  console.log(`  Resume with: /config-audit ${lastNext}`);
}

process.exit(0);
