import { readFileSync } from 'fs';
import { parse } from 'yaml';
import path from 'path';
import type { AppConfig, NovelsConfig } from './types.ts';

const CONFIG_DIR = path.resolve(process.cwd(), 'config');

export function loadAppConfig(): AppConfig {
  const raw = readFileSync(path.join(CONFIG_DIR, '.config.yaml'), 'utf-8');
  const config = parse(raw) as AppConfig;

  if (!config.server?.port) throw new Error('Config missing server.port');
  if (!config.selenium?.remoteUrl) throw new Error('Config missing selenium.remoteUrl');
  if (!config.cache?.basePath) throw new Error('Config missing cache.basePath');
  if (!config.addons?.directory) throw new Error('Config missing addons.directory');

  return config;
}

export function loadNovelsConfig(): NovelsConfig {
  const raw = readFileSync(path.join(CONFIG_DIR, 'novels.yaml'), 'utf-8');
  const config = parse(raw) as NovelsConfig;

  if (!Array.isArray(config.novels)) throw new Error('novels.yaml must have a top-level "novels" array');

  for (const novel of config.novels) {
    if (!novel.slug) throw new Error(`Novel entry missing slug: ${JSON.stringify(novel)}`);
    if (!novel.type) throw new Error(`Novel "${novel.slug}" missing type`);
    if (novel.type !== 'epub' && novel.type !== 'web-scraped') {
      throw new Error(`Novel "${novel.slug}" has unknown type "${novel.type}"`);
    }
    if (!novel.source?.url && !novel.source?.urls?.length) {
      throw new Error(`Novel "${novel.slug}" missing source.url or source.urls`);
    }
  }

  return config;
}
