import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { execSync } from 'child_process'

// Derive version from git tags; fall back to commit hash
function getGitVersion() {
  try {
    // Attempt to fetch tags in case of a shallow clone (e.g. CI/CD)
    try {
      execSync('git fetch --tags', { stdio: 'ignore' });
    } catch (e) {
      // Ignore if fetch fails
    }

    // Only include --dirty locally (development), omit in production to prevent false "dirty" flags
    const isProd = process.env.NODE_ENV === 'production' || process.env.CI;
    const describeCmd = isProd ? 'git describe --tags --always' : 'git describe --tags --always --dirty';
    const raw = execSync(describeCmd, { stdio: ['pipe', 'pipe', 'ignore'] })
      .toString()
      .trim();

    // If it's just a commit hash (no tags found)
    if (/^[0-9a-f]{7,}$/.test(raw)) {
      return `v0.0.0-${raw}`;
    }

    // Otherwise, return raw (e.g., v0.1.1-5-g4a9f6b6 or v1.2.0)

    // Exact tag (e.g., v1.2.0)
    return raw;
  } catch {
    return 'dev';
  }
}

const APP_VERSION = getGitVersion();
console.log(`[vite] App version: ${APP_VERSION}`);

// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), tailwindcss()],
  define: {
    // Injected at build time — available as __APP_VERSION__ in source
    __APP_VERSION__: JSON.stringify(APP_VERSION),
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true,
      }
    }
  }
})
