import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import type { PreRenderedAsset } from 'rollup';

/**
 * Keep emitted PNG paths aligned with manifest `file` (relative to repo `frontend/assets/`).
 * Default Vite/Rollup naming flattens everything into `dist/assets/*.png`, which breaks
 * inspection of the image and confuses deployment checks.
 */
function manifestRelativeAssetStem(assetInfo: PreRenderedAsset): string | undefined {
  const candidates = [
    ...(assetInfo.originalFileNames ?? []),
    assetInfo.originalFileName,
    ...(assetInfo.names ?? []),
  ].filter((s): s is string => typeof s === 'string' && s.length > 0);

  for (const ofn of candidates) {
    const n = ofn.replace(/\\/g, '/');
    const marker = '/assets/';
    const i = n.indexOf(marker);
    if (i !== -1) {
      const rel = n.slice(i + marker.length).replace(/\.png$/i, '');
      if (rel) return rel;
    }
    const parts = n.split('/');
    const ai = parts.lastIndexOf('assets');
    if (ai !== -1 && parts[ai + 1]) {
      const rel = parts.slice(ai + 1).join('/').replace(/\.png$/i, '');
      if (rel) return rel;
    }
  }
  return undefined;
}

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': '/src',
    },
  },
  server: {
    host: '0.0.0.0',
    port: 5173,
    strictPort: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
      '/ws': {
        target: 'ws://localhost:8080',
        ws: true,
      },
    },
  },
  build: {
    target: 'es2020',
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          pixi: ['pixi.js'],
          react: ['react', 'react-dom'],
        },
        assetFileNames(assetInfo) {
          if (assetInfo.names?.some((n) => n.endsWith('.png'))) {
            const stem = manifestRelativeAssetStem(assetInfo);
            if (stem) {
              return `assets/${stem}-[hash][extname]`;
            }
          }
          return 'assets/[name]-[hash][extname]';
        },
      },
    },
  },
});
