import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { VitePWA } from "vite-plugin-pwa";

const DESKTOP_API_ORIGIN = "https://sproutclaw.shumengya.top";

export default defineConfig(({ mode }) => {
	const isDesktop = mode === "desktop";

	return {
		plugins: [
			react(),
			VitePWA({
				registerType: "prompt",
				includeAssets: ["logo.png", "logo192.png", "logo512.png"],
				manifest: {
					name: "萌小芽",
					short_name: "萌小芽",
					description: "树萌芽智能 AI 助手 Web 客户端",
					theme_color: "#f7f8fb",
					background_color: "#f7f8fb",
					display: "standalone",
					orientation: "portrait-primary",
					scope: "/",
					start_url: "/",
					lang: "zh-CN",
					icons: [
						{
							src: "logo192.png",
							sizes: "192x192",
							type: "image/png",
						},
						{
							src: "logo512.png",
							sizes: "512x512",
							type: "image/png",
						},
						{
							src: "logo512.png",
							sizes: "512x512",
							type: "image/png",
							purpose: "maskable",
						},
					],
				},
				workbox: {
					navigateFallback: "index.html",
					globPatterns: ["**/*.{js,css,html,png,ico}"],
					globIgnores: ["**/fonts/**"],
					runtimeCaching: isDesktop
						? [
								{
									urlPattern: new RegExp(
										`^${DESKTOP_API_ORIGIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/api/`,
									),
									handler: "NetworkOnly",
								},
							]
						: [
								{
									urlPattern: /^\/api\//,
									handler: "NetworkOnly",
								},
							],
				},
				devOptions: {
					enabled: false,
				},
			}),
		],
		build: {
			outDir: isDesktop ? "dist-desketop" : "dist",
			emptyOutDir: true,
			rollupOptions: {
				output: {
					manualChunks(id) {
						if (id.includes("node_modules/react-dom") || id.includes("node_modules/react/")) {
							return "react-vendor";
						}
						if (id.includes("node_modules/react-router") || id.includes("node_modules/@remix-run/router")) {
							return "router-vendor";
						}
						if (id.includes("node_modules/@xterm")) {
							return "xterm-vendor";
						}
						if (
							id.includes("node_modules/highlight.js") ||
							id.includes("node_modules/marked") ||
							id.includes("node_modules/github-markdown-css")
						) {
							return "markdown-vendor";
						}
					},
				},
			},
		},
		server: {
			host: "0.0.0.0",
			port: 5173,
			proxy: {
				"/api": {
					target: "http://127.0.0.1:19133",
					ws: true,
				},
			},
		},
	};
});
