import { readFileSync } from 'fs';
import { z } from 'zod';

const councilPromptSetSchema = z.object({
  arbiter: z.string().min(1),
  free_thinker: z.string().min(1),
  grounder: z.string().min(1).optional(),
  writer: z.string().min(1).optional(),
}).strict();

export const councilScaffoldSchema = z.object({
  generated_at: z.string().optional(),
  version: z.string().optional(),
  prompts: z.object({
    D: councilPromptSetSchema,
    P: councilPromptSetSchema,
    meta_arbiter: z.string().min(1),
  }).strict(),
}).strict();

export type CouncilScaffold = z.infer<typeof councilScaffoldSchema>;

export function loadCouncilScaffold(path: string): CouncilScaffold {
  const raw = readFileSync(path, 'utf8');
  return councilScaffoldSchema.parse(JSON.parse(raw));
}

export function loadCouncilScaffoldSafe(path?: string): CouncilScaffold | undefined {
  if (!path) {
    return undefined;
  }
  try {
    return loadCouncilScaffold(path);
  } catch {
    return undefined;
  }
}
