import { defineConfig, loadEnv, ConfigEnv, UserConfig, CSSOptions } from "vite";
import { resolve } from "path";
import { wrapperEnv } from "./build/getEnv";
import { createProxy } from "./build/proxy";
import { createVitePlugins } from "./build/plugins";
import UnoCSS from "unocss/vite";
import pkg from "./package.json";
import dayjs from "dayjs";

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
    pkg: { dependencies, devDependencies, name, version },
    lastBuildTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
};

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
    const root = process.cwd();
    const env = loadEnv(mode, root);
    const viteEnv = wrapperEnv(env);

    return {
        base: viteEnv.VITE_PUBLIC_PATH,
        root,
        resolve: {
            alias: {
                "@": resolve(__dirname, "./src")
            }
        },
        define: {
            __APP_INFO__: JSON.stringify(__APP_INFO__)
        },
        // 关键：通过 as CSSOptions 断言类型
        css: {
            preprocessorOptions: {
                scss: {
                    silenceDeprecations: ["legacy-js-api"],
                    additionalData: `@use "@/styles/var.scss" as *;`
                }
            },
            warnings: {
                filter: (warning: any) => {
                    return !warning.message.includes('A nested style rule cannot start with "a"');
                }
            }
        } as CSSOptions, // 类型断言，解决类型不匹配
        server: {
            host: "0.0.0.0",
            port: viteEnv.VITE_PORT,
            open: viteEnv.VITE_OPEN,
            cors: true,
            proxy: createProxy(viteEnv.VITE_PROXY)
        },
        plugins: [...createVitePlugins(viteEnv), UnoCSS()],
        esbuild: {
            pure: viteEnv.VITE_DROP_CONSOLE ? ["console.log", "debugger"] : []
        },
        build: {
            outDir: "dist",
            minify: "esbuild",
            reportCompressedSize: false,
            chunkSizeWarningLimit: 2000,
            rollupOptions: {
                output: {
                    chunkFileNames: "assets/js/[name]-[hash].js",
                    entryFileNames: "assets/js/[name]-[hash].js",
                    assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
                }
            }
        }
    };
});
