import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'
import { fileURLToPath } from 'url'
import path from 'path'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

const isTauri = !!process.env.TAURI_ENV_PLATFORM

export default defineConfig({
  envPrefix: ['VITE_', 'TAURI_ENV_'],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      // Habilitar compilación de templates en runtime para componentes dinámicos
      'vue': 'vue/dist/vue.esm-bundler.js'
    }
  },
  plugins: [
    vue(),
    // PWA only in web builds (not Tauri)
    ...(!isTauri ? [VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.svg', 'icons/*.svg', 'icons/*.png'],
      devOptions: {
        enabled: true,
        type: 'module',
        suppressWarnings: true
      },
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
        navigateFallbackDenylist: [/^\/api\//],
        // Don't cache API calls - let them go directly to network
        runtimeCaching: []
      },
      manifest: {
        name: 'Agent UI',
        short_name: 'AgentUI',
        description: 'Dynamic canvas for Claude Code interaction via WebMCP',
        theme_color: '#0f0f14',
        background_color: '#0f0f14',
        display: 'standalone',
        display_override: ['window-controls-overlay'],
        orientation: 'any',
        start_url: '/',
        scope: '/',
        categories: ['developer', 'utilities'],
        icons: [
          {
            src: 'icons/icon.svg',
            sizes: 'any',
            type: 'image/svg+xml',
            purpose: 'any'
          },
          {
            src: 'icons/icon-192.png',
            sizes: '192x192',
            type: 'image/png'
          },
          {
            src: 'icons/icon-512.png',
            sizes: '512x512',
            type: 'image/png'
          },
          {
            src: 'icons/icon-maskable-512.png',
            sizes: '512x512',
            type: 'image/png',
            purpose: 'maskable'
          }
        ]
      }
    })] : [])
  ],
  server: {
    port: 4100,
    host: true,
    allowedHosts: ['z590.interno.com', 'z590.nucleoriofrio.com', 'localhost'],
    cors: true,
    proxy: {
      '/api': 'http://localhost:4101'
    },
    watch: {
      usePolling: false
    }
  },
  build: {
    sourcemap: true
  }
})
