#!/usr/bin/env node

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

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

const ASSETS = [
  {
    url: 'https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.30.2/cytoscape.min.js',
    output: path.join(__dirname, '../../site/public/js/cytoscape.min.js'),
  },
  {
    url: 'https://unpkg.com/cytoscape-cose-bilkent@1.6.4/cytoscape-cose-bilkent.js',
    output: path.join(__dirname, '../../site/public/js/cytoscape-cose-bilkent.js'),
  },
];

function downloadFile(url, outputPath) {
  return new Promise((resolve, reject) => {
    https.get(url, (res) => {
      if (res.statusCode !== 200) {
        reject(new Error(`HTTP ${res.statusCode}: ${url}`));
        return;
      }
      const chunks = [];
      res.on('data', (c) => chunks.push(c));
      res.on('end', () => {
        fs.mkdirSync(path.dirname(outputPath), { recursive: true });
        fs.writeFileSync(outputPath, Buffer.concat(chunks));
        resolve();
      });
    }).on('error', reject);
  });
}

const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;

for (const { url, output } of ASSETS) {
  if (fs.existsSync(output)) {
    const age = Date.now() - fs.statSync(output).mtime.getTime();
    if (age < MAX_AGE_MS) {
      console.log(`✅ ${path.basename(output)} already present (${fs.statSync(output).size} bytes)`);
      continue;
    }
  }
  process.stdout.write(`📥 ${path.basename(output)}... `);
  await downloadFile(url, output);
  console.log(`${fs.statSync(output).size} bytes`);
}
