#!/usr/bin/env node
/**
 * Cross-platform clean script
 * Removes build artifacts
 */

import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';

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

// Navigate to project root (two levels up from builder/)
const rootDir = path.join(__dirname, '../..');

console.log('🧹 Cleaning build artifacts...\n');

// Files to delete in root directory
const rootPatterns = [
    '*.js',
    '*.d.ts',
    '*.d.ts.map',
    '*.js.map'
];

// Directories to exclude
const excludeDirs = ['node_modules', '.git', 'msger-native'];

function deleteFile(filePath: string): boolean {
    try {
        fs.unlinkSync(filePath);
        return true;
    } catch {
        return false;
    }
}

function matchesPattern(filename: string, pattern: string): boolean {
    const regex = new RegExp('^' + pattern.replace(/\*/g, '.*').replace(/\./g, '\\.') + '$');
    return regex.test(filename);
}

// Clean root directory
let deletedCount = 0;
const files = fs.readdirSync(rootDir);

for (const file of files) {
    const filePath = path.join(rootDir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) continue;

    for (const pattern of rootPatterns) {
        if (matchesPattern(file, pattern)) {
            if (deleteFile(filePath)) {
                console.log(`  ✓ Deleted: ${file}`);
                deletedCount++;
            }
            break;
        }
    }
}

console.log(`\n📁 Cleaned ${deletedCount} files from root directory`);

// Clean Rust build artifacts
console.log('\n🦀 Cleaning Rust build artifacts...');
const nativeDir = path.join(rootDir, 'msger-native');

if (fs.existsSync(nativeDir)) {
    try {
        execSync('cargo clean', {
            cwd: nativeDir,
            stdio: 'inherit'
        });
        console.log('  ✓ Rust artifacts cleaned');
    } catch (error) {
        console.error('  ✗ Failed to run cargo clean');
    }
} else {
    console.log('  ⚠️  msger-native directory not found');
}

console.log('\n✨ Clean complete!\n');
