#!/usr/bin/env node

/**
 * Download highlightjs-copy CSS file from CDN
 * The JS is bundled in highlight-bundle.min.js, but CSS needs to be separate
 *
 * Usage:
 *   node scripts/download/download-highlightjs-copy-css.js
 *
 * This downloads the CSS to public/styles/
 */

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);

// Version of highlightjs-copy to use (should match build-highlight-bundle.js)
const HIGHLIGHTJS_COPY_VERSION = '1.0.6';
const COPY_CSS_URL = `https://unpkg.com/highlightjs-copy@${HIGHLIGHTJS_COPY_VERSION}/dist/highlightjs-copy.min.css`;

function downloadFile(url, outputPath) {
  return new Promise((resolve, reject) => {
    const dir = path.dirname(outputPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }

    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', () => {
        fs.writeFileSync(outputPath, data);
        resolve();
      });
    }).on('error', reject);
  });
}

async function downloadCopyButtonCSS() {
  try {
    const outputPath = path.join(__dirname, '../../site/public/styles/highlightjs-copy.min.css');

    // Check if CSS file already exists and is recent (less than 7 days old)
    if (fs.existsSync(outputPath)) {
      const stats = fs.statSync(outputPath);
      const fileAge = Date.now() - stats.mtime.getTime();
      const maxAge = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds

      if (fileAge < maxAge) {
        const fileSizeKB = Math.round(stats.size / 1024);
        const ageDays = Math.round(fileAge / (24 * 60 * 60 * 1000));

        console.log('✅ highlightjs-copy CSS already exists and is recent!');
        console.log(`📁 File: ${outputPath}`);
        console.log(`📊 Size: ${fileSizeKB}KB`);
        console.log(`⏰ Age: ${ageDays}d (created: ${stats.mtime.toLocaleDateString()})`);
        console.log('💡 To force re-download, delete the file or wait 7 days');
        return;
      } else {
        console.log('🔄 CSS file exists but is older than 7 days, downloading...');
      }
    }

    console.log('📥 Downloading highlightjs-copy CSS...');
    console.log(`📦 Version: ${HIGHLIGHTJS_COPY_VERSION}`);
    console.log(`🔗 URL: ${COPY_CSS_URL}`);

    await downloadFile(COPY_CSS_URL, outputPath);

    const stats = fs.statSync(outputPath);
    const fileSizeKB = Math.round(stats.size / 1024);

    console.log('✅ highlightjs-copy CSS downloaded successfully!');
    console.log(`📁 Output: ${outputPath}`);
    console.log(`📊 Size: ${fileSizeKB}KB`);
    console.log('');
    console.log('💡 Next step: Include this CSS file in your HTML template');

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

downloadCopyButtonCSS();
