import { VOCAB } from '@/lib/white-label/constants';

/**
 * ${VOCAB.factory} - Multi-Platform Deployment Targets
 * Generates platform-specific packaging configurations
 * 
 * Supported targets:
 * - Web (default): Next.js standalone / static export
 * - Desktop: Electron or Tauri wrapper
 * - Mobile: PWA manifest + Capacitor config
 * - All: Combined deployment for all platforms
 */

export type DeploymentPlatform = 'web' | 'desktop-electron' | 'desktop-tauri' | 'mobile-pwa' | 'mobile-capacitor';

export interface DeploymentTarget {
  id: DeploymentPlatform;
  label: string;
  shortLabel: string;
  icon: string;
  description: string;
  outputFormats: string[];
  requirements: string[];
  recommended: boolean;
}

export interface DeploymentConfig {
  targets: DeploymentPlatform[];
  appName: string;
  appId?: string; // reverse-domain for mobile (com.company.app)
  version?: string;
  icon?: string; // path to app icon
  splash?: string; // path to splash screen
  electronConfig?: {
    windowWidth: number;
    windowHeight: number;
    autoUpdater: boolean;
    trayIcon: boolean;
  };
  tauriConfig?: {
    windowWidth: number;
    windowHeight: number;
    systemTray: boolean;
  };
  pwaConfig?: {
    themeColor: string;
    backgroundColor: string;
    display: 'standalone' | 'fullscreen' | 'minimal-ui';
    orientation: 'portrait' | 'landscape' | 'any';
  };
  capacitorConfig?: {
    iosTeamId?: string;
    androidKeystore?: string;
  };
}

export const DEPLOYMENT_TARGETS: DeploymentTarget[] = [
  {
    id: 'web',
    label: 'Web Application',
    shortLabel: 'Web',
    icon: '🌐',
    description: 'Deploy as a standard web application. Accessible from any browser on any device.',
    outputFormats: ['Next.js Standalone', 'Static Export', 'Docker Container'],
    requirements: ['Node.js runtime or static host'],
    recommended: true,
  },
  {
    id: 'desktop-electron',
    label: 'Desktop (Electron)',
    shortLabel: 'Electron',
    icon: '🖥️',
    description: 'Package as a native desktop app for Windows, macOS, and Linux using Electron.',
    outputFormats: ['.exe (Windows)', '.dmg (macOS)', '.AppImage (Linux)', '.deb (Debian)'],
    requirements: ['electron', 'electron-builder'],
    recommended: true,
  },
  {
    id: 'desktop-tauri',
    label: 'Desktop (Tauri)',
    shortLabel: 'Tauri',
    icon: '⚡',
    description: 'Lightweight native desktop app using Tauri (Rust). Smaller binary, lower memory.',
    outputFormats: ['.msi (Windows)', '.dmg (macOS)', '.AppImage (Linux)'],
    requirements: ['Rust toolchain', '@tauri-apps/cli'],
    recommended: false,
  },
  {
    id: 'mobile-pwa',
    label: 'Mobile (PWA)',
    shortLabel: 'PWA',
    icon: '📱',
    description: 'Progressive Web App. Installable from the browser, works offline, no app store needed.',
    outputFormats: ['manifest.json', 'Service Worker', 'Offline Cache'],
    requirements: ['HTTPS hosting', 'Service Worker support'],
    recommended: true,
  },
  {
    id: 'mobile-capacitor',
    label: 'Mobile (Capacitor)',
    shortLabel: 'Native',
    icon: '📲',
    description: 'Native iOS and Android app using Capacitor. Distribute via App Store and Google Play.',
    outputFormats: ['.ipa (iOS)', '.apk / .aab (Android)'],
    requirements: ['@capacitor/core', '@capacitor/cli', 'Xcode (iOS)', 'Android Studio'],
    recommended: false,
  },
];

export const DEFAULT_DEPLOYMENT_CONFIG: DeploymentConfig = {
  targets: ['web'],
  appName: 'Generated App',
  version: '1.0.0',
  electronConfig: {
    windowWidth: 1280,
    windowHeight: 800,
    autoUpdater: true,
    trayIcon: false,
  },
  tauriConfig: {
    windowWidth: 1280,
    windowHeight: 800,
    systemTray: false,
  },
  pwaConfig: {
    themeColor: '#0C1222',
    backgroundColor: '#0C1222',
    display: 'standalone',
    orientation: 'any',
  },
};

export function getDeploymentTarget(id: DeploymentPlatform): DeploymentTarget {
  return DEPLOYMENT_TARGETS.find(t => t.id === id) || DEPLOYMENT_TARGETS[0];
}

/**
 * Generate Electron main process entry point
 */
export function generateElectronMain(config: DeploymentConfig): string {
  const { electronConfig, appName } = config;
  const w = electronConfig?.windowWidth || 1280;
  const h = electronConfig?.windowHeight || 800;

  return `const { app, BrowserWindow, Menu, Tray } = require('electron');
const path = require('path');
const { spawn } = require('child_process');

let mainWindow;
let tray = null;
let serverProcess = null;

const PORT = 3847;
const isDev = process.argv.includes('--dev');

function startServer() {
  if (isDev) return Promise.resolve();
  
  return new Promise((resolve, reject) => {
    const serverPath = path.join(process.resourcesPath, 'server', 'server.js');
    serverProcess = spawn('node', [serverPath], {
      env: { ...process.env, PORT: String(PORT), NODE_ENV: 'production' },
      stdio: 'pipe'
    });
    
    serverProcess.stdout.on('data', (data) => {
      const msg = data.toString();
      console.log('[Server]', msg);
      if (msg.includes('ready') || msg.includes('started')) resolve();
    });
    
    serverProcess.stderr.on('data', (data) => console.error('[Server Error]', data.toString()));
    serverProcess.on('error', reject);
    
    // Fallback resolve after 5s
    setTimeout(resolve, 5000);
  });
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: ${w},
    height: ${h},
    title: '${appName}',
    icon: path.join(__dirname, 'assets', 'icon.png'),
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    },
    backgroundColor: '#0C1222',
    show: false,
  });

  mainWindow.once('ready-to-show', () => mainWindow.show());
  
  const url = isDev ? 'http://localhost:3000' : \`http://localhost:\${PORT}\`;
  mainWindow.loadURL(url);

  mainWindow.on('closed', () => { mainWindow = null; });
}

${electronConfig?.trayIcon ? `
function createTray() {
  tray = new Tray(path.join(__dirname, 'assets', 'tray-icon.png'));
  tray.setToolTip('${appName}');
  tray.on('click', () => {
    if (mainWindow) mainWindow.show();
  });
}
` : ''}

app.whenReady().then(async () => {
  await startServer();
  createWindow();
  ${electronConfig?.trayIcon ? 'createTray();' : ''}
  
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('quit', () => {
  if (serverProcess) serverProcess.kill();
});
`;
}

/**
 * Generate Electron preload script
 */
export function generateElectronPreload(): string {
  return `const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  platform: process.platform,
  isDesktop: true,
  appVersion: require('../package.json').version,
  onUpdateAvailable: (callback) => ipcRenderer.on('update-available', callback),
  onUpdateDownloaded: (callback) => ipcRenderer.on('update-downloaded', callback),
  installUpdate: () => ipcRenderer.send('install-update'),
  minimize: () => ipcRenderer.send('minimize-window'),
  maximize: () => ipcRenderer.send('maximize-window'),
  close: () => ipcRenderer.send('close-window'),
});
`;
}

/**
 * Generate electron-builder.yml config
 */
export function generateElectronBuilderConfig(config: DeploymentConfig): string {
  const appId = config.appId || `com.ghostfoundry.${config.appName.toLowerCase().replace(/\s+/g, '-')}`;
  
  return `appId: "${appId}"
productName: "${config.appName}"
copyright: "Copyright © ${new Date().getFullYear()}"

directories:
  output: dist
  buildResources: assets

files:
  - "**/*"
  - "!src/**"
  - "!docs/**"
  - "!*.md"

extraResources:
  - from: ".next/standalone"
    to: "server"
    filter:
      - "**/*"

win:
  target:
    - target: nsis
      arch:
        - x64
  icon: assets/icon.ico
  artifactName: \${productName}-Setup-\${version}.\${ext}

nsis:
  oneClick: false
  perMachine: false
  allowToChangeInstallationDirectory: true
  deleteAppDataOnUninstall: false
  createDesktopShortcut: true
  createStartMenuShortcut: true

mac:
  target:
    - target: dmg
      arch:
        - x64
        - arm64
  icon: assets/icon.icns
  category: public.app-category.business
  hardenedRuntime: true

linux:
  target:
    - AppImage
    - deb
  icon: assets
  category: Office

publish:
  provider: generic
  url: "https://updates.ghostfoundry.ai"
`;
}

/**
 * Generate package.json for Electron app
 */
export function generateElectronPackageJson(config: DeploymentConfig): string {
  return JSON.stringify({
    name: config.appName.toLowerCase().replace(/\s+/g, '-'),
    version: config.version || '1.0.0',
    description: `${config.appName} - Desktop Application`,
    main: 'electron/main.js',
    scripts: {
      'dev': 'concurrently "next dev" "wait-on http://localhost:3000 && electron . --dev"',
      'build': 'next build && electron-builder build --config electron-builder.yml',
      'build:win': 'next build && electron-builder build --win --config electron-builder.yml',
      'build:mac': 'next build && electron-builder build --mac --config electron-builder.yml',
      'build:linux': 'next build && electron-builder build --linux --config electron-builder.yml',
      'postinstall': 'electron-builder install-app-deps',
    },
    devDependencies: {
      'electron': '^28.0.0',
      'electron-builder': '^24.9.0',
      'concurrently': '^8.2.0',
      'wait-on': '^7.2.0',
    },
  }, null, 2);
}

/**
 * Generate PWA manifest.json
 */
export function generatePWAManifest(config: DeploymentConfig): string {
  const pwa = config.pwaConfig || DEFAULT_DEPLOYMENT_CONFIG.pwaConfig!;
  
  return JSON.stringify({
    name: config.appName,
    short_name: config.appName.substring(0, 12),
    description: `${config.appName} - Progressive Web Application`,
    start_url: '/',
    display: pwa.display,
    orientation: pwa.orientation,
    theme_color: pwa.themeColor,
    background_color: pwa.backgroundColor,
    icons: [
      { src: '/icons/icon-72x72.png', sizes: '72x72', type: 'image/png' },
      { src: '/icons/icon-96x96.png', sizes: '96x96', type: 'image/png' },
      { src: '/icons/icon-128x128.png', sizes: '128x128', type: 'image/png' },
      { src: '/icons/icon-144x144.png', sizes: '144x144', type: 'image/png' },
      { src: '/icons/icon-152x152.png', sizes: '152x152', type: 'image/png' },
      { src: '/icons/icon-192x192.png', sizes: '192x192', type: 'image/png', purpose: 'any maskable' },
      { src: '/icons/icon-384x384.png', sizes: '384x384', type: 'image/png' },
      { src: '/icons/icon-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' },
    ],
    categories: ['business', 'productivity'],
    screenshots: [
      { src: '/screenshots/desktop.png', sizes: '1280x800', type: 'image/png', form_factor: 'wide' },
      { src: '/screenshots/mobile.png', sizes: '390x844', type: 'image/png', form_factor: 'narrow' },
    ],
  }, null, 2);
}

/**
 * Generate PWA service worker
 */
export function generateServiceWorker(config: DeploymentConfig): string {
  return `// ${config.appName} - Service Worker
const CACHE_NAME = '${config.appName.toLowerCase().replace(/\s+/g, '-')}-v${config.version || '1'}';
const OFFLINE_URL = '/offline.html';

const PRECACHE_URLS = [
  '/',
  '/offline.html',
  '/icons/icon-192x192.png',
  '/icons/icon-512x512.png',
];

// Install event - precache critical resources
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(() => self.skipWaiting())
  );
});

// Activate event - clean old caches
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(
        keys.filter(key => key !== CACHE_NAME).map(key => caches.delete(key))
      )
    ).then(() => self.clients.claim())
  );
});

// Fetch event - network-first with cache fallback
self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;
  
  // Skip API requests
  if (event.request.url.includes('/api/')) return;
  
  event.respondWith(
    fetch(event.request)
      .then(response => {
        // Cache successful responses
        if (response.ok) {
          const clone = response.clone();
          caches.open(CACHE_NAME).then(cache => cache.put(event.request, clone));
        }
        return response;
      })
      .catch(() => {
        // Serve from cache on network failure
        return caches.match(event.request)
          .then(cached => cached || caches.match(OFFLINE_URL));
      })
  );
});

// Background sync for offline form submissions
self.addEventListener('sync', (event) => {
  if (event.tag === 'sync-pending') {
    event.waitUntil(syncPendingRequests());
  }
});

async function syncPendingRequests() {
  // Implementation for syncing offline mutations
  console.log('[SW] Syncing pending requests...');
}
`;
}

/**
 * Generate Capacitor configuration
 */
export function generateCapacitorConfig(config: DeploymentConfig): string {
  const appId = config.appId || `com.ghostfoundry.${config.appName.toLowerCase().replace(/\s+/g, '-')}`;
  
  return JSON.stringify({
    appId,
    appName: config.appName,
    webDir: 'out',
    server: {
      androidScheme: 'https',
    },
    plugins: {
      SplashScreen: {
        launchShowDuration: 2000,
        backgroundColor: '#0C1222',
        showSpinner: true,
        spinnerColor: '#0EA5E9',
      },
      StatusBar: {
        style: 'DARK',
        backgroundColor: '#0C1222',
      },
      Keyboard: {
        resize: 'body',
        resizeOnFullScreen: true,
      },
    },
    ios: {
      contentInset: 'automatic',
    },
    android: {
      allowMixedContent: false,
    },
  }, null, 2);
}

/**
 * Generate Tauri configuration
 */
export function generateTauriConfig(config: DeploymentConfig): string {
  const appId = config.appId || `com.ghostfoundry.${config.appName.toLowerCase().replace(/\s+/g, '-')}`;
  const tauri = config.tauriConfig || DEFAULT_DEPLOYMENT_CONFIG.tauriConfig!;
  
  return JSON.stringify({
    $schema: '../node_modules/@tauri-apps/cli/schema.json',
    build: {
      beforeBuildCommand: 'npm run build',
      beforeDevCommand: 'npm run dev',
      devPath: 'http://localhost:3000',
      distDir: '../out',
    },
    package: {
      productName: config.appName,
      version: config.version || '1.0.0',
    },
    tauri: {
      allowlist: {
        all: false,
        shell: { all: false, open: true },
        dialog: { all: true },
        fs: { all: false, readFile: true, writeFile: true, scope: ['$APP/*'] },
        notification: { all: true },
      },
      bundle: {
        active: true,
        identifier: appId,
        icon: [
          'icons/32x32.png',
          'icons/128x128.png',
          'icons/128x128@2x.png',
          'icons/icon.icns',
          'icons/icon.ico',
        ],
        targets: 'all',
        windows: {
          wix: { language: 'en-US' },
          nsis: { installerIcon: 'icons/icon.ico' },
        },
      },
      security: {
        csp: null,
      },
      windows: [
        {
          title: config.appName,
          width: tauri.windowWidth,
          height: tauri.windowHeight,
          resizable: true,
          fullscreen: false,
        },
      ],
      systemTray: tauri.systemTray ? { iconPath: 'icons/icon.png', iconAsTemplate: true } : undefined,
    },
  }, null, 2);
}

/**
 * Generate offline.html fallback page for PWA
 */
export function generateOfflinePage(config: DeploymentConfig): string {
  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${config.appName} - Offline</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { 
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      background: #0C1222; color: #e2e8f0;
      display: flex; align-items: center; justify-content: center;
      min-height: 100vh; padding: 2rem;
    }
    .container { text-align: center; max-width: 400px; }
    .icon { font-size: 4rem; margin-bottom: 1.5rem; }
    h1 { font-size: 1.5rem; margin-bottom: 0.75rem; color: #f1f5f9; }
    p { color: #94a3b8; line-height: 1.6; margin-bottom: 1.5rem; }
    button {
      background: linear-gradient(135deg, #0EA5E9, #FDBA74);
      color: white; border: none; padding: 0.75rem 2rem;
      border-radius: 0.5rem; font-size: 1rem; cursor: pointer;
    }
    button:hover { opacity: 0.9; }
  </style>
</head>
<body>
  <div class="container">
    <div class="icon">📡</div>
    <h1>You're Offline</h1>
    <p>${config.appName} needs an internet connection for some features. Check your connection and try again.</p>
    <button onclick="window.location.reload()">Try Again</button>
  </div>
</body>
</html>`;
}
