import { z } from 'zod';

const HEX_64 = /^[0-9a-fA-F]{64}$/;

const schema = z.object({
  // Spec 0071: 32-byte hex master key for envelope encryption of all DB
  // credentials (backend_credentials + connector_secrets). Generated by
  // `pnpm run docker:setup` if missing. Loss = unrecoverable credentials.
  ZENO_MASTER_KEY: z.string().regex(HEX_64, 'ZENO_MASTER_KEY must be 64 hex chars (32 bytes)'),
  LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warn', 'error']).default('info'),
  WORKSPACE_DIR: z.string().default('/workspace'),
  LOGS_RETENTION_DAYS: z.coerce.number().int().min(1).max(365).default(7),
});

export type Config = {
  masterKey: Buffer;
  logLevel: 'trace' | 'debug' | 'info' | 'warn' | 'error';
  workspaceDir: string;
  logsRetentionDays: number;
};

export function loadConfig(): Config {
  const parsed = schema.safeParse(process.env);
  if (!parsed.success) {
    const issues = parsed.error.issues
      .map((issue) => `${issue.path.join('.')}: ${issue.message}`)
      .join('; ');
    throw new Error(`Invalid environment: ${issues}`);
  }
  const env = parsed.data;
  return {
    masterKey: Buffer.from(env.ZENO_MASTER_KEY, 'hex'),
    logLevel: env.LOG_LEVEL,
    workspaceDir: env.WORKSPACE_DIR,
    logsRetentionDays: env.LOGS_RETENTION_DAYS,
  };
}
