// Shared config access for the Hermes reply-brain.
// Reads the SAME files as /root/hermes-router.py — single source of truth, zero duplication.
import { readFileSync } from 'fs';
import { execFileSync } from 'child_process';

export const HERMES = {
  env: '/root/.hermes/.env',
  personas: '/root/.hermes/personas.json',
  blocklist: '/root/.hermes/blocklist.json',
  agenda: '/root/.hermes/agenda.json',
  style: '/root/.hermes/adrian-style.md',
  contextScript: '/root/hermes-context.py',
} as const;

export type Ctx = {
  time_window?: string;
  at_work?: boolean;
  on_vacation?: boolean;
  [k: string]: unknown;
};

export function loadJson<T>(path: string, fallback: T): T {
  try {
    return JSON.parse(readFileSync(path, 'utf8')) as T;
  } catch {
    return fallback;
  }
}

export function loadStyle(): string {
  try {
    return readFileSync(HERMES.style, 'utf8');
  } catch {
    return 'Ești Adrian. Scrie scurt și natural pe WhatsApp, în română, ca un om real.';
  }
}

// Runs the existing Python context engine (pontaj Supabase + Brussels clock).
// Mirrors hermes-router.py get_context(): on any failure -> {} (never throws).
export function getContext(): Ctx {
  try {
    const out = execFileSync('python3', [HERMES.contextScript], { timeout: 20000, encoding: 'utf8' });
    const lastLine = out.trim().split('\n').pop() || '{}';
    return JSON.parse(lastLine) as Ctx;
  } catch {
    return {};
  }
}

export function getOpenRouterKey(): string {
  try {
    for (const line of readFileSync(HERMES.env, 'utf8').split('\n')) {
      if (line.startsWith('OPENROUTER_API_KEY=')) {
        return line.slice('OPENROUTER_API_KEY='.length).trim();
      }
    }
  } catch {
    /* fall through to env */
  }
  return process.env.OPENROUTER_API_KEY ?? '';
}
