import { cpSync, existsSync, mkdirSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
import { siteConfig } from './config/site'

export default defineNuxtConfig({
  compatibilityDate: '2025-01-01',
  devtools: { enabled: true },

  runtimeConfig: {
    public: {
      icp: '',
      psBeian: '',
    },
  },

  css: ['~/assets/css/main.css'],

  modules: [
    '@nuxtjs/tailwindcss',
    '@nuxtjs/color-mode',
    '@nuxt/content',
    '@nuxtjs/sitemap',
  ],

  app: {
    head: {
      htmlAttrs: { lang: 'zh-CN' },
      charset: 'utf-8',
      viewport: 'width=device-width, initial-scale=1',
      meta: [
        { name: 'description', content: siteConfig.description },
        { property: 'og:type', content: 'website' },
        { property: 'og:locale', content: 'zh_CN' },
      ],
    },
  },

  colorMode: {
    classSuffix: '',
    preference: 'system',
    fallback: 'light',
  },

  content: {
    build: {
      markdown: {
        toc: {
          depth: 3,
        },
        highlight: {
          theme: {
            light: 'github-light',
            dark: 'github-dark',
          },
          langs: [
            'javascript', 'js', 'cjs', 'mjs', 'jsx',
            'typescript', 'ts', 'cts', 'mts', 'tsx',
            'vue', 'css', 'html', 'json',
            'bash', 'sh', 'shell', 'zsh', 'shellscript',
            'python', 'py', 'go', 'rust', 'java', 'c', 'cpp', 'csharp',
            'ruby', 'php', 'swift', 'kotlin', 'scala',
            'sql', 'graphql', 'protobuf',
            'yaml', 'yml', 'toml', 'xml', 'ini',
            'markdown', 'md', 'mdc',
            'dockerfile', 'docker', 'makefile', 'nginx', 'apache',
            'diff', 'git-commit', 'git-rebase',
            'powershell', 'batch', 'lua', 'perl', 'r', 'dart', 'elixir', 'erlang', 'haskell'
          ],
        },
      },
    },
  },

  mdc: {
    components: {
      prose: true,
    },
  },

  site: {
    url: siteConfig.url,
    name: siteConfig.title,
  },

  nitro: {
    prerender: {
      routes: ['/sitemap.xml'],
    },
  },

  hooks: {
    'nitro:build:public-assets'(nitro: any) {
      const root = process.cwd()
      const contentDir = join(root, 'content', 'posts')
      if (!existsSync(contentDir)) return

      const publicDir = join(root, '.output', 'public', 'posts')

      const posts = readdirSync(contentDir, { withFileTypes: true })
        .filter(d => d.isDirectory())
        .map(d => d.name)

      let copied = 0
      for (const slug of posts) {
        const imgDir = join(contentDir, slug, 'img')
        if (!existsSync(imgDir)) continue

        const destDir = join(publicDir, slug, 'img')
        mkdirSync(destDir, { recursive: true })
        cpSync(imgDir, destDir, { recursive: true })
        copied++
      }

      if (copied > 0) {
        console.log(`[content-assets] Copied images for ${copied} posts`)
      }
    },
  },
})
