import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath, URL } from 'node:url';
import { defineConfig, type ProxyOptions } from 'vite';
import react from '@vitejs/plugin-react';

interface MockConfig {
  readonly mirror: string;
  readonly paths: readonly string[];
}

/** `mc.config.json` (written by `multiclone scaffold --capture`) proxies captured API calls to the mirror. */
function mockProxy(): Record<string, ProxyOptions> {
  const file = fileURLToPath(new URL('./mc.config.json', import.meta.url));
  if (!existsSync(file)) return {};
  const parsed: unknown = JSON.parse(readFileSync(file, 'utf8'));
  if (!isMockConfig(parsed)) return {};
  const mirror = process.env.MC_MIRROR ?? parsed.mirror;
  return Object.fromEntries(parsed.paths.map((path) => [path, { target: mirror, changeOrigin: true }]));
}

function isMockConfig(value: unknown): value is MockConfig {
  if (typeof value !== 'object' || value === null) return false;
  const { mirror, paths } = value as { mirror?: unknown; paths?: unknown };
  return (
    typeof mirror === 'string' &&
    Array.isArray(paths) &&
    paths.every((path) => typeof path === 'string')
  );
}

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
  },
  server: { host: '127.0.0.1', port: {{port}}, strictPort: true, proxy: mockProxy() },
});
