#!/usr/bin/env node

/**
 * Update Cache Version - Unified Cache Busting
 *
 * Updates all HTML files with a consistent cache-busting version string.
 * Format: v={package.version}.{timestamp}
 * Example: v=0.1.0.1760201234
 *
 * This ensures all assets (CSS, JS) are loaded with the same version,
 * solving the inconsistent cache busting problem.
 */

const fs = require('fs');
const path = require('path');
const packageJson = require('../package.json');

// Generate cache version: package version + timestamp
const CACHE_VERSION = `${packageJson.version}.${Date.now()}`;

// HTML files to update (relative to project root)
const HTML_FILES = [
  'public/index.html',
  'public/docs.html',
  'public/faq.html',
  'public/researcher.html',
  'public/implementer.html',
  'public/leader.html',
  'public/about.html',
  'public/privacy.html',
  'public/blog.html',
  'public/blog-post.html',
  'public/docs-viewer.html',
  'public/api-reference.html',
  'public/media-inquiry.html',
  'public/case-submission.html',
  'public/koha.html',
  'public/check-version.html'
];

/**
 * Update cache version in a file
 * Replaces all instances of ?v=X with ?v={CACHE_VERSION}
 */
function updateCacheVersion(filePath) {
  try {
    const fullPath = path.join(__dirname, '..', filePath);

    if (!fs.existsSync(fullPath)) {
      console.warn(`⚠️  File not found: ${filePath}`);
      return false;
    }

    let content = fs.readFileSync(fullPath, 'utf8');
    const originalContent = content;

    // Pattern: ?v=ANYTHING → ?v={CACHE_VERSION}
    // Matches: ?v=1.0.4, ?v=1759833751, ?v=1.0.5.1760123456
    content = content.replace(/\?v=[0-9a-zA-Z._-]+/g, `?v=${CACHE_VERSION}`);

    // Only write if changed
    if (content !== originalContent) {
      fs.writeFileSync(fullPath, content, 'utf8');

      // Count replacements
      const matches = originalContent.match(/\?v=[0-9a-zA-Z._-]+/g) || [];
      console.log(`✅ ${filePath}: Updated ${matches.length} cache version(s)`);
      return true;
    } else {
      console.log(`ℹ️  ${filePath}: No changes needed`);
      return false;
    }

  } catch (error) {
    console.error(`❌ Error updating ${filePath}:`, error.message);
    return false;
  }
}

/**
 * Main execution
 */
function main() {
  console.log('');
  console.log('═'.repeat(70));
  console.log('  Tractatus - Cache Version Update');
  console.log('═'.repeat(70));
  console.log('');
  console.log(`📦 Package version: ${packageJson.version}`);
  console.log(`🔄 New cache version: ${CACHE_VERSION}`);
  console.log('');

  let updatedCount = 0;
  let totalFiles = 0;

  HTML_FILES.forEach(file => {
    totalFiles++;
    if (updateCacheVersion(file)) {
      updatedCount++;
    }
  });

  console.log('');
  console.log('═'.repeat(70));
  console.log(`  Summary: ${updatedCount}/${totalFiles} files updated`);
  console.log('═'.repeat(70));
  console.log('');

  if (updatedCount > 0) {
    console.log('✅ Cache version updated successfully!');
    console.log(`   All assets will now use: ?v=${CACHE_VERSION}`);
  } else {
    console.log('ℹ️  No files needed updating');
  }
  console.log('');
}

// Run if called directly
if (require.main === module) {
  main();
}

module.exports = { updateCacheVersion, CACHE_VERSION };
