#!/usr/bin/env node
/**
 * Cleanup script: Remove unnecessary build artifacts to keep user's computer clean
 * - Removes Rust debug builds (keep only release)
 * - Removes incremental compilation artifacts
 * - Keeps only the final release binary
 */

import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

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

const mk3Dir = path.join(__dirname, '..', 'mk3-tui');
const targetDir = path.join(mk3Dir, 'target');

if (!fs.existsSync(targetDir)) {
  // No build artifacts to clean
  process.exit(0);
}

const binaryName = process.platform === 'win32' ? 'mk3-tui.exe' : 'mk3-tui';
const releaseBinary = path.join(targetDir, 'release', binaryName);

// Check if release binary exists - if so, we can safely clean up
if (fs.existsSync(releaseBinary)) {
  let cleanedSize = 0;
  
  try {
    // Remove debug build (if exists) - saves ~200-300MB
    const debugDir = path.join(targetDir, 'debug');
    if (fs.existsSync(debugDir)) {
      const stats = getDirSize(debugDir);
      fs.rmSync(debugDir, { recursive: true, force: true });
      cleanedSize += stats;
    }
    
    // Remove incremental compilation artifacts (keeps builds faster but uses disk)
    const incrementalDir = path.join(targetDir, 'release', '.fingerprint');
    const incrementalDeps = path.join(targetDir, 'release', 'deps');
    const incrementalIncremental = path.join(targetDir, 'incremental');
    
    if (fs.existsSync(incrementalDir)) {
      cleanedSize += getDirSize(incrementalDir);
      fs.rmSync(incrementalDir, { recursive: true, force: true });
    }
    
    // Keep deps/ folder (needed for linking), but remove .fingerprint
    // Remove incremental compilation metadata (can be rebuilt)
    if (fs.existsSync(incrementalIncremental)) {
      cleanedSize += getDirSize(incrementalIncremental);
      fs.rmSync(incrementalIncremental, { recursive: true, force: true });
    }
    
    // Calculate cleaned size in MB
    const cleanedMB = (cleanedSize / (1024 * 1024)).toFixed(1);
    if (cleanedMB > 0.1) {
      // Only log if we cleaned something meaningful
      // Silent cleanup - don't bother user with details
    }
  } catch (error) {
    // Silent fail - cleanup is best-effort
    // Don't break install if cleanup fails
  }
}

/**
 * Calculate directory size recursively
 */
function getDirSize(dirPath) {
  let size = 0;
  try {
    const entries = fs.readdirSync(dirPath, { withFileTypes: true });
    for (const entry of entries) {
      const entryPath = path.join(dirPath, entry.name);
      if (entry.isDirectory()) {
        size += getDirSize(entryPath);
      } else {
        try {
          const stats = fs.statSync(entryPath);
          size += stats.size;
        } catch {
          // Ignore errors
        }
      }
    }
  } catch {
    // Ignore errors
  }
  return size;
}

// Export for use in other scripts
export function cleanupBuildArtifacts() {
  // This runs the cleanup logic above
  // (code is already executed when script runs directly)
}

