/**
 * GET /api/recommend/report - Generate HTML report from recommendation results
 *
 * Query params:
 *   - data: Base64-encoded JSON of recommendation response
 *   - lang: Language (en, ko, ja, zh) - default: en
 */

import type { Env, RecommendationResult, BandwidthEstimate } from '../types';
import { jsonResponse, escapeHtml } from '../utils';

interface ReportData {
  recommendations: RecommendationResult[];
  bandwidth_estimate: BandwidthEstimate & {
    calculation_note?: string;
  };
  total_candidates: number;
  request?: {
    tech_stack: string[];
    expected_users: number;
    use_case: string;
  };
}

const i18n: Record<string, Record<string, string>> = {
  en: {
    title: 'Server Recommendation Report',
    subtitle: 'AI-Powered Infrastructure Analysis',
    requirements: 'Requirements',
    techStack: 'Tech Stack',
    expectedUsers: 'Expected Users',
    useCase: 'Use Case',
    bandwidthEstimate: 'Bandwidth Estimate',
    monthly: 'Monthly',
    daily: 'Daily',
    category: 'Category',
    recommendations: 'Recommendations',
    budget: 'Budget',
    balanced: 'Balanced',
    premium: 'Premium',
    specs: 'Specifications',
    vcpu: 'vCPU',
    memory: 'Memory',
    storage: 'Storage',
    region: 'Region',
    price: 'Price',
    score: 'Score',
    analysis: 'Analysis',
    techFit: 'Tech Fit',
    capacity: 'Capacity',
    costEfficiency: 'Cost Efficiency',
    scalability: 'Scalability',
    bandwidthInfo: 'Bandwidth Cost',
    includedTransfer: 'Included Transfer',
    overagePrice: 'Overage Price',
    estimatedUsage: 'Estimated Usage',
    estimatedOverage: 'Estimated Overage',
    estimatedCost: 'Est. Overage Cost',
    totalCost: 'Total Est. Cost',
    warning: 'Warning',
    generatedAt: 'Generated at',
    poweredBy: 'Powered by Cloud Orchestrator',
    printNote: 'Print this page or save as PDF using your browser',
    perMonth: '/month',
    perGb: '/GB',
  },
  ko: {
    title: '서버 추천 보고서',
    subtitle: 'AI 기반 인프라 분석',
    requirements: '요구사항',
    techStack: '기술 스택',
    expectedUsers: '예상 사용자',
    useCase: '용도',
    bandwidthEstimate: '대역폭 예측',
    monthly: '월간',
    daily: '일간',
    category: '카테고리',
    recommendations: '추천 서버',
    budget: '예산형',
    balanced: '균형형',
    premium: '프리미엄',
    specs: '사양',
    vcpu: 'vCPU',
    memory: '메모리',
    storage: '스토리지',
    region: '리전',
    price: '가격',
    score: '점수',
    analysis: '분석',
    techFit: '기술 적합성',
    capacity: '용량',
    costEfficiency: '비용 효율성',
    scalability: '확장성',
    bandwidthInfo: '대역폭 비용',
    includedTransfer: '기본 제공',
    overagePrice: '초과 요금',
    estimatedUsage: '예상 사용량',
    estimatedOverage: '예상 초과량',
    estimatedCost: '예상 초과 비용',
    totalCost: '총 예상 비용',
    warning: '주의',
    generatedAt: '생성 시각',
    poweredBy: 'Cloud Orchestrator 제공',
    printNote: '브라우저에서 인쇄하거나 PDF로 저장하세요',
    perMonth: '/월',
    perGb: '/GB',
  },
};

function getLabels(lang: string): Record<string, string> {
  return i18n[lang] || i18n['en'];
}

function formatPrice(price: number, currency: string): string {
  if (currency === 'KRW') {
    return `₩${Math.round(price).toLocaleString()}`;
  }
  return `$${price.toFixed(2)}`;
}

function getTierLabel(index: number, labels: Record<string, string>): string {
  const tiers = [labels.budget, labels.balanced, labels.premium];
  return tiers[index] || `Option ${index + 1}`;
}

function getTierColor(index: number): string {
  const colors = ['#10b981', '#3b82f6', '#8b5cf6']; // green, blue, purple
  return colors[index] || '#6b7280';
}

export async function handleReport(
  request: Request,
  env: Env,
  corsHeaders: Record<string, string>
): Promise<Response> {
  try {
    const url = new URL(request.url);
    const dataParam = url.searchParams.get('data');
    const lang = url.searchParams.get('lang') || 'en';

    if (!dataParam) {
      return jsonResponse(
        { error: 'Missing data parameter. Provide Base64-encoded recommendation data.' },
        400,
        corsHeaders
      );
    }

    // Decode Base64 data
    let reportData: ReportData;
    try {
      const decoded = atob(dataParam);
      reportData = JSON.parse(decoded) as ReportData;
    } catch {
      return jsonResponse(
        { error: 'Invalid data parameter. Must be valid Base64-encoded JSON.' },
        400,
        corsHeaders
      );
    }

    if (!reportData.recommendations || reportData.recommendations.length === 0) {
      return jsonResponse(
        { error: 'No recommendations in data.' },
        400,
        corsHeaders
      );
    }

    const labels = getLabels(lang);
    const html = generateReportHTML(reportData, labels, lang);

    return new Response(html, {
      status: 200,
      headers: {
        'Content-Type': 'text/html; charset=utf-8',
        ...corsHeaders,
      },
    });
  } catch (error) {
    console.error('[Report] Error:', error);
    return jsonResponse(
      { error: 'Failed to generate report' },
      500,
      corsHeaders
    );
  }
}

function generateReportHTML(
  data: ReportData,
  labels: Record<string, string>,
  lang: string
): string {
  const { recommendations, bandwidth_estimate, request } = data;
  const now = new Date().toISOString();

  const recommendationCards = recommendations.map((rec, index) => {
    const { server, score, analysis, bandwidth_info } = rec;
    const tierLabel = getTierLabel(index, labels);
    const tierColor = getTierColor(index);
    const currency = server.currency || 'USD';

    return `
      <div class="recommendation-card" style="border-left-color: ${tierColor}">
        <div class="card-header">
          <div class="tier-badge" style="background-color: ${tierColor}">${tierLabel}</div>
          <div class="score">${labels.score}: ${score}/100</div>
        </div>

        <h3 class="server-name">${escapeHtml(server.provider_name)} - ${escapeHtml(server.instance_name)}</h3>

        <div class="specs-grid">
          <div class="spec-item">
            <span class="spec-label">${labels.vcpu}</span>
            <span class="spec-value">${server.vcpu} cores</span>
          </div>
          <div class="spec-item">
            <span class="spec-label">${labels.memory}</span>
            <span class="spec-value">${server.memory_gb} GB</span>
          </div>
          <div class="spec-item">
            <span class="spec-label">${labels.storage}</span>
            <span class="spec-value">${server.storage_gb} GB</span>
          </div>
          <div class="spec-item">
            <span class="spec-label">${labels.region}</span>
            <span class="spec-value">${escapeHtml(server.region_name)}</span>
          </div>
          <div class="spec-item highlight">
            <span class="spec-label">${labels.price}</span>
            <span class="spec-value">${formatPrice(server.monthly_price, currency)}${labels.perMonth}</span>
          </div>
        </div>

        ${bandwidth_info ? `
        <div class="bandwidth-section">
          <h4>${labels.bandwidthInfo}</h4>
          <div class="bandwidth-grid">
            <div class="bandwidth-item">
              <span class="bw-label">${labels.includedTransfer}</span>
              <span class="bw-value">${bandwidth_info.included_transfer_tb} TB${labels.perMonth}</span>
            </div>
            <div class="bandwidth-item">
              <span class="bw-label">${labels.overagePrice}</span>
              <span class="bw-value">${bandwidth_info.currency === 'KRW' ? `₩${bandwidth_info.overage_cost_per_gb}` : `$${bandwidth_info.overage_cost_per_gb.toFixed(4)}`}${labels.perGb}</span>
            </div>
            <div class="bandwidth-item">
              <span class="bw-label">${labels.estimatedUsage}</span>
              <span class="bw-value">${bandwidth_info.estimated_monthly_tb} TB</span>
            </div>
            ${bandwidth_info.estimated_overage_tb > 0 ? `
            <div class="bandwidth-item warning">
              <span class="bw-label">${labels.estimatedOverage}</span>
              <span class="bw-value">${bandwidth_info.estimated_overage_tb} TB</span>
            </div>
            <div class="bandwidth-item warning">
              <span class="bw-label">${labels.estimatedCost}</span>
              <span class="bw-value">+${bandwidth_info.currency === 'KRW' ? `₩${Math.round(bandwidth_info.estimated_overage_cost).toLocaleString()}` : `$${bandwidth_info.estimated_overage_cost.toFixed(2)}`}</span>
            </div>
            ` : ''}
            <div class="bandwidth-item total">
              <span class="bw-label">${labels.totalCost}</span>
              <span class="bw-value">${bandwidth_info.currency === 'KRW' ? `₩${Math.round(bandwidth_info.total_estimated_cost).toLocaleString()}` : `$${bandwidth_info.total_estimated_cost.toFixed(2)}`}${labels.perMonth}</span>
            </div>
          </div>
          ${bandwidth_info.warning ? `<div class="bandwidth-warning">${escapeHtml(bandwidth_info.warning)}</div>` : ''}
        </div>
        ` : ''}

        <div class="analysis-section">
          <h4>${labels.analysis}</h4>
          <div class="analysis-item">
            <strong>${labels.techFit}:</strong> ${escapeHtml(analysis.tech_fit)}
          </div>
          <div class="analysis-item">
            <strong>${labels.capacity}:</strong> ${escapeHtml(analysis.capacity)}
          </div>
          <div class="analysis-item">
            <strong>${labels.costEfficiency}:</strong> ${escapeHtml(analysis.cost_efficiency)}
          </div>
          <div class="analysis-item">
            <strong>${labels.scalability}:</strong> ${escapeHtml(analysis.scalability)}
          </div>
        </div>
      </div>
    `;
  }).join('\n');

  return `<!DOCTYPE html>
<html lang="${lang}">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${labels.title}</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      line-height: 1.6;
      color: #1f2937;
      background: #f9fafb;
      padding: 2rem;
    }

    .container {
      max-width: 1000px;
      margin: 0 auto;
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
      padding: 2rem;
    }

    header {
      text-align: center;
      margin-bottom: 2rem;
      padding-bottom: 1.5rem;
      border-bottom: 2px solid #e5e7eb;
    }

    h1 {
      font-size: 1.875rem;
      color: #111827;
      margin-bottom: 0.5rem;
    }

    .subtitle {
      color: #6b7280;
      font-size: 1rem;
    }

    .print-note {
      background: #fef3c7;
      color: #92400e;
      padding: 0.75rem 1rem;
      border-radius: 8px;
      margin-bottom: 1.5rem;
      font-size: 0.875rem;
      text-align: center;
    }

    .requirements-section {
      background: #f3f4f6;
      padding: 1.5rem;
      border-radius: 8px;
      margin-bottom: 2rem;
    }

    .requirements-section h2 {
      font-size: 1.25rem;
      margin-bottom: 1rem;
      color: #374151;
    }

    .req-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 1rem;
    }

    .req-item {
      background: white;
      padding: 1rem;
      border-radius: 6px;
    }

    .req-label {
      font-size: 0.75rem;
      color: #6b7280;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }

    .req-value {
      font-size: 1rem;
      font-weight: 600;
      color: #111827;
      margin-top: 0.25rem;
    }

    .bandwidth-estimate {
      background: #eff6ff;
      padding: 1rem;
      border-radius: 6px;
      margin-top: 1rem;
    }

    .bandwidth-estimate h3 {
      font-size: 0.875rem;
      color: #1e40af;
      margin-bottom: 0.5rem;
    }

    .bw-stats {
      display: flex;
      gap: 2rem;
      flex-wrap: wrap;
    }

    .bw-stat {
      font-size: 0.875rem;
    }

    .bw-stat strong {
      color: #1e40af;
    }

    h2.section-title {
      font-size: 1.5rem;
      color: #111827;
      margin-bottom: 1.5rem;
    }

    .recommendation-card {
      background: white;
      border: 1px solid #e5e7eb;
      border-left: 4px solid;
      border-radius: 8px;
      padding: 1.5rem;
      margin-bottom: 1.5rem;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1rem;
    }

    .tier-badge {
      color: white;
      padding: 0.25rem 0.75rem;
      border-radius: 9999px;
      font-size: 0.75rem;
      font-weight: 600;
      text-transform: uppercase;
    }

    .score {
      font-weight: 600;
      color: #374151;
    }

    .server-name {
      font-size: 1.25rem;
      color: #111827;
      margin-bottom: 1rem;
    }

    .specs-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 0.75rem;
      margin-bottom: 1.5rem;
    }

    .spec-item {
      background: #f9fafb;
      padding: 0.75rem;
      border-radius: 6px;
    }

    .spec-item.highlight {
      background: #ecfdf5;
    }

    .spec-label {
      display: block;
      font-size: 0.75rem;
      color: #6b7280;
    }

    .spec-value {
      display: block;
      font-weight: 600;
      color: #111827;
    }

    .bandwidth-section {
      background: #fefce8;
      padding: 1rem;
      border-radius: 6px;
      margin-bottom: 1rem;
    }

    .bandwidth-section h4 {
      font-size: 0.875rem;
      color: #854d0e;
      margin-bottom: 0.75rem;
    }

    .bandwidth-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
      gap: 0.5rem;
    }

    .bandwidth-item {
      display: flex;
      justify-content: space-between;
      font-size: 0.8125rem;
      padding: 0.25rem 0;
    }

    .bandwidth-item.warning {
      color: #dc2626;
    }

    .bandwidth-item.total {
      font-weight: 600;
      border-top: 1px solid #fde68a;
      padding-top: 0.5rem;
      margin-top: 0.25rem;
    }

    .bw-label {
      color: #6b7280;
    }

    .bw-value {
      font-weight: 500;
    }

    .bandwidth-warning {
      margin-top: 0.75rem;
      padding: 0.5rem;
      background: #fef2f2;
      color: #991b1b;
      border-radius: 4px;
      font-size: 0.8125rem;
    }

    .analysis-section h4 {
      font-size: 0.875rem;
      color: #374151;
      margin-bottom: 0.75rem;
    }

    .analysis-item {
      font-size: 0.875rem;
      margin-bottom: 0.5rem;
      color: #4b5563;
    }

    .analysis-item strong {
      color: #374151;
    }

    footer {
      margin-top: 2rem;
      padding-top: 1.5rem;
      border-top: 1px solid #e5e7eb;
      text-align: center;
      color: #9ca3af;
      font-size: 0.875rem;
    }

    @media print {
      body {
        background: white;
        padding: 0;
      }

      .container {
        box-shadow: none;
        padding: 1rem;
      }

      .print-note {
        display: none;
      }

      .recommendation-card {
        break-inside: avoid;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <header>
      <h1>${labels.title}</h1>
      <p class="subtitle">${labels.subtitle}</p>
    </header>

    <div class="print-note">
      🖨️ ${labels.printNote}
    </div>

    ${request ? `
    <section class="requirements-section">
      <h2>${labels.requirements}</h2>
      <div class="req-grid">
        <div class="req-item">
          <span class="req-label">${labels.techStack}</span>
          <span class="req-value">${escapeHtml(request.tech_stack.join(', '))}</span>
        </div>
        <div class="req-item">
          <span class="req-label">${labels.expectedUsers}</span>
          <span class="req-value">${request.expected_users.toLocaleString()}</span>
        </div>
        <div class="req-item">
          <span class="req-label">${labels.useCase}</span>
          <span class="req-value">${escapeHtml(request.use_case)}</span>
        </div>
      </div>

      ${bandwidth_estimate ? `
      <div class="bandwidth-estimate">
        <h3>${labels.bandwidthEstimate}</h3>
        <div class="bw-stats">
          <span class="bw-stat"><strong>${labels.monthly}:</strong> ${bandwidth_estimate.monthly_tb >= 1 ? `${bandwidth_estimate.monthly_tb} TB` : `${bandwidth_estimate.monthly_gb} GB`}</span>
          <span class="bw-stat"><strong>${labels.daily}:</strong> ${bandwidth_estimate.daily_gb} GB</span>
          <span class="bw-stat"><strong>${labels.category}:</strong> ${bandwidth_estimate.category}</span>
        </div>
      </div>
      ` : ''}
    </section>
    ` : ''}

    <section>
      <h2 class="section-title">${labels.recommendations}</h2>
      ${recommendationCards}
    </section>

    <footer>
      <p>${labels.generatedAt}: ${now}</p>
      <p>${labels.poweredBy}</p>
    </footer>
  </div>
</body>
</html>`;
}
