#!/usr/bin/env node

/**
 * Types Checksum Generation Script
 * 
 * Generates and commits a checksum of TypeScript definition files
 * to catch accidental API changes.
 * 
 * @author Matthew Raymer
 * @version 1.0.0
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const TYPES_CHECKSUM_FILE = path.join(__dirname, '..', 'types-checksum.txt');
const DIST_TYPES_DIR = path.join(__dirname, '..', 'dist', 'esm');

/**
 * Generate checksum of all TypeScript definition files
 * @returns {string} Checksum of all .d.ts files
 */
function generateTypesChecksum() {
  try {
    if (!fs.existsSync(DIST_TYPES_DIR)) {
      console.error('❌ Dist types directory not found. Run "npm run build" first.');
      process.exit(1);
    }

    // Get all .d.ts files in dist/esm
    const typeFiles = execSync(`find "${DIST_TYPES_DIR}" -name "*.d.ts" -type f`, { encoding: 'utf8' })
      .trim()
      .split('\n')
      .filter(file => file.length > 0);

    if (typeFiles.length === 0) {
      console.warn('⚠️  No TypeScript definition files found in dist/esm');
      return '';
    }

    console.log(`📁 Found ${typeFiles.length} TypeScript definition files:`);
    typeFiles.forEach(file => console.log(`   ${file}`));

    // Generate checksum of all type files
    const checksum = execSync(`cat ${typeFiles.join(' ')} | shasum -a 256`, { encoding: 'utf8' })
      .trim()
      .split(' ')[0];

    return checksum;
  } catch (error) {
    console.error('Error generating types checksum:', error.message);
    return '';
  }
}

/**
 * Generate and commit types checksum
 */
function generateAndCommitChecksum() {
  console.log('🔍 Generating types checksum...');

  const checksum = generateTypesChecksum();
  
  if (!checksum) {
    console.error('❌ Could not generate types checksum');
    process.exit(1);
  }

  console.log(`📝 Generated checksum: ${checksum}`);

  // Write checksum to file
  const checksumContent = `${checksum}\n# Generated on ${new Date().toISOString()}\n# Files: dist/esm/**/*.d.ts\n`;
  fs.writeFileSync(TYPES_CHECKSUM_FILE, checksumContent);

  console.log(`💾 Written checksum to ${TYPES_CHECKSUM_FILE}`);

  // Check if file is already committed
  try {
    execSync(`git ls-files --error-unmatch "${TYPES_CHECKSUM_FILE}"`, { stdio: 'ignore' });
    console.log('✅ Types checksum file is already tracked by git');
  } catch (error) {
    // File is not tracked, add it
    console.log('📝 Adding types checksum file to git...');
    execSync(`git add "${TYPES_CHECKSUM_FILE}"`);
    console.log('✅ Types checksum file added to git');
  }

  console.log('✅ Types checksum generation complete');
}

// Run the generation
generateAndCommitChecksum();
