import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import { execSync } from 'child_process';

const APP_VERSION = (() => {
	// 1. Use APP_VERSION env var (passed via Docker --build-arg or .env)
	if (process.env.APP_VERSION && process.env.APP_VERSION !== '0.0.0') {
		return process.env.APP_VERSION;
	}
	// 2. Fall back to latest git tag + short commit hash (works in local dev with .git)
	try {
		const tag = execSync('git describe --tags --abbrev=0', { encoding: 'utf8' }).trim();
		const commit = execSync('git rev-parse --short HEAD', { encoding: 'utf8' }).trim();
		return `${tag}+${commit}`;
	} catch {
		return '0.0.0';
	}
})();

export default defineConfig({
	define: {
		__APP_VERSION__: JSON.stringify(APP_VERSION)
	},
	plugins: [sveltekit()],
	server: {
		proxy: {
		'/api/agent/gradio': {
			target: process.env.GRADIO_URL || 'http://127.0.0.1:7860',
			changeOrigin: true,
			secure: false,
			rewrite: (path) => path.replace(/^\/api\/agent\/gradio/, ''),
			ws: true
		},
			'/api': {
				target: process.env.BACKEND_URL || 'http://127.0.0.1:8000',
				changeOrigin: true,
				secure: false,
				rewrite: (path) => path.replace(/^\/api/, '/api')
			},
			'/ws': {
				target: (process.env.BACKEND_URL || 'http://127.0.0.1:8000').replace(/^http/, 'ws'),
				ws: true,
				changeOrigin: true,
				secure: false
			}
		}
	}
});
