#!/usr/bin/env node

/**
 * Download highlight.js CSS theme from CDN
 * This downloads the GitHub Dark theme for syntax highlighting
 *
 * Usage:
 *   node scripts/download/download-highlight-css.js
 */

import fs from 'fs';
import path from 'path';
import https from 'https';
import { fileURLToPath } from 'url';

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

const CDN_URL = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css';
const OUTPUT_PATH = path.join(__dirname, '../../site/public/styles/highlight-github-dark.min.css');

function downloadFile(url, outputPath) {
  return new Promise((resolve, reject) => {
    https.get(url, (response) => {
      if (response.statusCode !== 200) {
        reject(new Error(`HTTP ${response.statusCode}: ${url}`));
        return;
      }

      let data = '';
      response.on('data', (chunk) => data += chunk);
      response.on('end', () => {
        // Ensure output directory exists
        const outputDir = path.dirname(outputPath);
        if (!fs.existsSync(outputDir)) {
          fs.mkdirSync(outputDir, { recursive: true });
        }

        // Add header comment to the CSS
        const cssWithHeader = `/*! Highlight.js GitHub Dark Theme
 * Downloaded from: ${url}
 * Generated on: ${new Date().toISOString()}
 */

${data}`;

        fs.writeFileSync(outputPath, cssWithHeader);
        resolve();
      });
    }).on('error', reject);
  });
}

async function downloadHighlightCss() {
  try {
    // Check if file already exists and is recent
    if (fs.existsSync(OUTPUT_PATH)) {
      const stats = fs.statSync(OUTPUT_PATH);
      const fileAge = Date.now() - stats.mtime.getTime();
      const maxAge = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds

      if (fileAge < maxAge) {
        const fileSizeBytes = stats.size;
        const ageHours = Math.round(fileAge / (60 * 60 * 1000));

        console.log('✅ Highlight.js CSS theme already exists and is recent!');
        console.log(`📁 File: ${OUTPUT_PATH}`);
        console.log(`📊 Size: ${fileSizeBytes} bytes`);
        console.log(`⏰ Age: ${ageHours}h (created: ${stats.mtime.toLocaleString()})`);
        console.log('💡 To force re-download, delete the file or wait 7 days');
        return;
      } else {
        console.log('🔄 CSS theme exists but is older than 7 days, re-downloading...');
      }
    }

    console.log('📥 Downloading highlight.js GitHub Dark theme...');
    console.log(`🔗 URL: ${CDN_URL}`);
    console.log(`📁 Output: ${OUTPUT_PATH}`);

    await downloadFile(CDN_URL, OUTPUT_PATH);

    const stats = fs.statSync(OUTPUT_PATH);
    const fileSizeBytes = stats.size;

    console.log('✅ Highlight.js CSS theme downloaded successfully!');
    console.log(`📁 File: ${OUTPUT_PATH}`);
    console.log(`📊 Size: ${fileSizeBytes} bytes`);
    console.log('🎨 Theme: GitHub Dark (optimized for dark mode)');
    console.log('');
    console.log('🚀 Ready to use! This theme provides:');
    console.log('  - Dark background suitable for dark mode UIs');
    console.log('  - High contrast syntax highlighting');
    console.log('  - GitHub-style color scheme');
    console.log('  - Support for all highlight.js languages');

  } catch (error) {
    console.error('❌ Error downloading CSS theme:', error.message);
    process.exit(1);
  }
}

downloadHighlightCss();
