import express from 'express';
import fetch from 'node-fetch';

const router = express.Router();

// Einfacher HTTP-Proxy ohne Playwright
router.get('/', async (req, res) => {
  try {
    const { code, pin } = req.query;
    
    if (!code) {
      return res.status(400).json({ 
        error: 'Code-Parameter ist erforderlich' 
      });
    }
    
    console.log(`📊 Einfacher Proxy für Code: ${code}, PIN: ${pin || 'nicht angegeben'}`);
    
    // Direkte HTTP-Anfrage an nuscore
    const nuscoreUrl = `https://ttde-apps.liga.nu/nuliga/nuscore-tt/meetings-list?code=${encodeURIComponent(code)}`;
    
    const response = await fetch(nuscoreUrl, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br',
        'DNT': '1',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1'
      },
      timeout: 30000
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    let html = await response.text();
    
    // Einfache HTML-Modifikationen
    html = html
      .replace(/<meta[^>]*http-equiv=["']content-security-policy["'][^>]*>/gi, '')
      .replace(/<meta[^>]*http-equiv=["']x-frame-options["'][^>]*>/gi, '')
      .replace(/<meta[^>]*http-equiv=["']x-content-type-options["'][^>]*>/gi, '');
    
    // Entferne Service Worker
    html = html.replace(
      /navigator\.serviceWorker\.register\([^)]+\)/g,
      '// Service Worker deaktiviert für Proxy'
    );
    
    // Korrigiere alle Asset-URLs zu absoluten URLs
    html = html.replace(
      /src="\.\//g,
      'src="https://ttde-apps.liga.nu/nuliga/nuscore-tt/'
    );
    html = html.replace(
      /href="\.\//g,
      'href="https://ttde-apps.liga.nu/nuliga/nuscore-tt/'
    );
    
    // Korrigiere auch URLs die bereits auf localhost zeigen
    html = html.replace(
      /src="http:\/\/localhost:3000\/nuliga\/nuscore-tt\//g,
      'src="https://ttde-apps.liga.nu/nuliga/nuscore-tt/'
    );
    html = html.replace(
      /href="http:\/\/localhost:3000\/nuliga\/nuscore-tt\//g,
      'href="https://ttde-apps.liga.nu/nuliga/nuscore-tt/'
    );
    
    // Entferne vorhandene base-Tags und füge unseres hinzu
    html = html.replace(
      /<base[^>]*>/gi,
      ''
    );
    
    // Füge base-Tag hinzu für korrekte Asset-Auflösung
    html = html.replace(
      '<head>',
      '<head><base href="https://ttde-apps.liga.nu/nuliga/nuscore-tt/">'
    );
    
    // Debug: Logge die HTML-Struktur
    console.log('🔍 HTML nach base-Tag:', html.substring(html.indexOf('<base'), html.indexOf('</head>') + 7));
    
    // Füge PIN-Injektion hinzu falls PIN vorhanden
    if (pin) {
      const pinScript = `
        <script>
          document.addEventListener('DOMContentLoaded', function() {
            setTimeout(function() {
              const pinInput = document.querySelector('input[type="password"][placeholder*="PIN"], input[placeholder*="Pin"], input[placeholder*="pin"]');
              if (pinInput) {
                pinInput.value = '${pin}';
                pinInput.dispatchEvent(new Event('input', { bubbles: true }));
                pinInput.dispatchEvent(new Event('change', { bubbles: true }));
                console.log('PIN automatisch eingefügt: ${pin}');
              }
            }, 2000);
          });
        </script>
      `;
      html = html.replace('</head>', `${pinScript}</head>`);
    }
    
    // CORS-Header setzen für iframe-Einbettung
    res.set({
      'Content-Type': 'text/html; charset=utf-8',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'X-Frame-Options': 'ALLOWALL',
      'Content-Security-Policy': "frame-ancestors *;",
      'Cache-Control': 'no-cache, no-store, must-revalidate'
    });
    
    res.send(html);
    console.log('✅ Einfacher Proxy erfolgreich');
    
  } catch (error) {
    console.error('❌ Einfacher Proxy-Fehler:', error);
    res.status(500).json({ 
      error: 'Fehler beim Laden der nuscore-Seite',
      details: error.message 
    });
  }
});

// Health-Check Route
router.get('/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    service: 'nuscore-simple-proxy',
    timestamp: new Date().toISOString()
  });
});

export default router;
