#!/usr/bin/env node

/**
 * Download external JavaScript dependencies
 * 
 * This script downloads the Recast SDK dependencies from unpkg
 * and places them in the assets/js/vendor directory.
 */

const https = require('https');
const fs = require('fs');
const path = require('path');

const VENDOR_DIR = path.join(__dirname, '..', 'assets', 'js', 'vendor');

const dependencies = [
    {
        name: 'jose',
        url: 'https://cdn.jsdelivr.net/npm/jose@6.0.12/+esm',
        filename: 'jose.js'
    },
    {
        name: 'recast-jwt',
        url: 'https://unpkg.com/@recast-sdk/recast-jwt@1.1.1/index.esm.js',
        filename: 'recast-jwt.js'
    },
    {
        name: 'recast-browser',
        url: 'https://unpkg.com/@recast-sdk/recast-browser@1.6.3/index.esm.js',
        filename: 'recast-browser.js'
    }
];

/**
 * Download a file from URL
 */
function downloadFile(url, dest) {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(dest);
        
        https.get(url, (response) => {
            if (response.statusCode === 302 || response.statusCode === 301) {
                // Handle redirects
                return downloadFile(response.headers.location, dest).then(resolve).catch(reject);
            }
            
            if (response.statusCode !== 200) {
                reject(new Error(`Failed to download ${url}: ${response.statusCode}`));
                return;
            }
            
            response.pipe(file);
            
            file.on('finish', () => {
                file.close();
                resolve();
            });
        }).on('error', (err) => {
            fs.unlink(dest, () => {});
            reject(err);
        });
        
        file.on('error', (err) => {
            fs.unlink(dest, () => {});
            reject(err);
        });
    });
}

/**
 * Main function
 */
async function main() {
    console.log('📦 Downloading JavaScript dependencies...\n');
    
    // Ensure vendor directory exists
    if (!fs.existsSync(VENDOR_DIR)) {
        fs.mkdirSync(VENDOR_DIR, { recursive: true });
        console.log(`✅ Created directory: ${VENDOR_DIR}\n`);
    }
    
    // Download each dependency
    for (const dep of dependencies) {
        const destPath = path.join(VENDOR_DIR, dep.filename);
        
        try {
            console.log(`⬇️  Downloading ${dep.name}...`);
            console.log(`   URL: ${dep.url}`);
            
            await downloadFile(dep.url, destPath);
            
            const stats = fs.statSync(destPath);
            console.log(`✅ Downloaded ${dep.filename} (${(stats.size / 1024).toFixed(2)} KB)\n`);
        } catch (error) {
            console.error(`❌ Failed to download ${dep.name}:`, error.message);
            process.exit(1);
        }
    }
    
    console.log('✅ All dependencies downloaded successfully!');
    console.log(`📁 Location: ${VENDOR_DIR}`);
}

// Run main function
main().catch((error) => {
    console.error('❌ Error:', error);
    process.exit(1);
});

