import i18nConfig from "./i18n.config";
import type { Strategies } from "@nuxtjs/i18n";
import { resolve } from "path";
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

// 尝试导入预生成的路由配置，如果文件不存在则使用默认路由
let prerenderRoutes = [
  "/",
  "/products",
  "/faq",
  "/contact",
  "/about",
  "/en",
  "/ja",
  "/en/products",
  "/ja/products",
  "/en/faq",
  "/ja/faq",
  "/en/contact",
  "/ja/contact",
  "/en/about",
  "/ja/about",
];

try {
  const __dirname = dirname(fileURLToPath(import.meta.url));
  const routesPath = join(__dirname, 'prerenderRoutes.json');
  prerenderRoutes = JSON.parse(readFileSync(routesPath, 'utf-8'));
  console.log(`已加载预渲染路由，共 ${prerenderRoutes.length} 条`);
} catch (err) {
  console.warn('未找到预渲染路由配置文件，使用默认路由');
}

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  devtools: { enabled: true },

  // 添加CSS
  css: [
    "~/assets/css/tailwind.css",
    "~/assets/css/styles.css",
    "~/assets/icomoon/style.css",
  ],

  // 模块
  modules: ["@nuxtjs/i18n", "@nuxt/content"],

  // content模块配置
  content: {
    // 配置 Markdown
    build: {
      markdown: {
        toc: {
          depth: 3,
          searchDepth: 3,
        },
        highlight: {
          // Theme used in all color schemes.
          theme: "github-light",
        },
      },
    },
  },

  // i18n 配置 (从外部文件加载)
  i18n: {
    ...i18nConfig,
    defaultLocale: i18nConfig.defaultLocale as "zh" | "en" | "ja" | undefined,
    strategy: i18nConfig.strategy as Strategies, // 显式类型转换 strategy
  },

  // Typescript 配置
  typescript: {
    strict: true,
    shim: false,
  },

  // PostCSS配置 (统一到这里)
  postcss: {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    },
  },

  // 编译配置
  build: {
    transpile: ["@nuxtjs/i18n"],
  },

  // 静态站点生成配置
  nitro: {
    prerender: {
      crawlLinks: false, // 不自动抓取链接
      routes: prerenderRoutes,
      ignore: ["/api/**", "/admin/**"],
      failOnError: false, // 遇到错误继续生成其他页面
    },
    // 添加图片本地化配置
    publicAssets: [
      {
        dir: "public",
        baseURL: "/",
      },
    ],
  },

  // 禁用 payload 提取，优化静态生成
  experimental: {
    payloadExtraction: false,
    renderJsonPayloads: false,
  },

  devServer: {
    host: "0.0.0.0",
  },

  compatibilityDate: "2025-05-07",
});