import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import YAML from 'yaml';

const siteRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../../..');

type SiteConfig = {
  site: {
    title: string;
    description: string;
    base_url: string;
    language: string;
    timezone: string;
    theme: string;
  };
  content: {
    posts_dir: string;
    assets_dir: string;
  };
  build: {
    astro_project: string;
    output_dir: string;
  };
};

const defaults: SiteConfig = {
  site: {
    title: 'Osaet',
    description: 'Personal blog',
    base_url: 'http://localhost:4321',
    language: 'zh-CN',
    timezone: 'Asia/Shanghai',
    theme: 'default'
  },
  content: {
    posts_dir: 'content/posts',
    assets_dir: 'content/assets'
  },
  build: {
    astro_project: 'frontend/site',
    output_dir: 'dist/site'
  }
};

function loadSiteConfig(): SiteConfig {
  try {
    const file = readFileSync(resolve(siteRoot, 'config/site.yaml'), 'utf8');
    const parsed = YAML.parse(file) ?? {};
    const siteOverrides = {
      ...parsed.site,
      ...(process.env.SITE_URL ? { base_url: process.env.SITE_URL } : {}),
      ...(process.env.PUBLIC_SITE_URL ? { base_url: process.env.PUBLIC_SITE_URL } : {})
    };

    return {
      site: { ...defaults.site, ...siteOverrides },
      content: { ...defaults.content, ...parsed.content },
      build: { ...defaults.build, ...parsed.build }
    };
  } catch {
    return {
      ...defaults,
      site: {
        ...defaults.site,
        ...(process.env.SITE_URL ? { base_url: process.env.SITE_URL } : {}),
        ...(process.env.PUBLIC_SITE_URL ? { base_url: process.env.PUBLIC_SITE_URL } : {})
      }
    };
  }
}

export const siteConfig = loadSiteConfig();
export const site = siteConfig.site;
