#!/usr/bin/env node
/**
 * ReePoe Clear Cache - Reset learned patterns
 */

const fs = require('fs');
const path = require('path');
const readline = require('readline');

async function clearCache() {
    const projectRoot = process.cwd();
    const storePath = path.join(projectRoot, 'data', 'mini_rag_store.json');
    const logPath = path.join(projectRoot, 'logs', 'mini_rag.log');
    
    console.log('\n╔═══════════════════════════════════════════════════════════╗');
    console.log('║  ReePoe Cache Clearing                                     ║');
    console.log('╚═══════════════════════════════════════════════════════════╝\n');
    
    // Check if files exist
    const storeExists = fs.existsSync(storePath);
    const logExists = fs.existsSync(logPath);
    
    if (!storeExists && !logExists) {
        console.log('✅ No cache files found - nothing to clear\n');
        return;
    }
    
    console.log('📋 Files to clear:');
    if (storeExists) {
        try {
            const stats = fs.statSync(storePath);
            const storeContent = fs.readFileSync(storePath, 'utf8');
            const patternCount = storeContent ? Object.keys(JSON.parse(storeContent)).length : 0;
            console.log(`   • ${storePath} (${patternCount} patterns, ${(stats.size / 1024).toFixed(1)} KB)`);
        } catch (e) {
            console.log(`   • ${storePath} (error reading file)`);
        }
    }
    if (logExists) {
        try {
            const stats = fs.statSync(logPath);
            console.log(`   • ${logPath} (${(stats.size / 1024).toFixed(1)} KB)`);
        } catch (e) {
            console.log(`   • ${logPath} (error reading file)`);
        }
    }
    console.log('');
    
    // Confirm
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    
    const answer = await new Promise((resolve) => {
        rl.question('⚠️  This will delete all learned patterns. Continue? (yes/no): ', (ans) => {
            rl.close();
            resolve(ans.trim().toLowerCase());
        });
    });
    
    if (answer !== 'yes' && answer !== 'y') {
        console.log('\n❌ Cancelled - cache not cleared\n');
        return;
    }
    
    // FIX #5: Try to clear via API first (to handle in-memory state/locks)
    try {
        const axios = require('axios');
        // Try default port 8000
        await axios.post('http://localhost:8000/internal/clear-cache', {}, { timeout: 2000 });
        console.log('✅ Cleared cache via running server API');
        return;
    } catch (e) {
        // Server not running or error, fall back to file system deletion
        // Continue to code below...
    }
    
    // Clear files
    try {
        if (storeExists) {
            // Ensure directory exists
            const storeDir = path.dirname(storePath);
            if (!fs.existsSync(storeDir)) {
                fs.mkdirSync(storeDir, { recursive: true });
            }
            fs.writeFileSync(storePath, '{}', 'utf8');
            console.log(`✅ Cleared: ${storePath}`);
        }
        if (logExists) {
            // Ensure directory exists
            const logDir = path.dirname(logPath);
            if (!fs.existsSync(logDir)) {
                fs.mkdirSync(logDir, { recursive: true });
            }
            fs.writeFileSync(logPath, '', 'utf8');
            console.log(`✅ Cleared: ${logPath}`);
        }
        console.log('\n✅ Cache cleared successfully!\n');
    } catch (error) {
        console.error(`\n❌ Error clearing cache: ${error.message}\n`);
        process.exit(1);
    }
}

clearCache().catch(error => {
    console.error(`❌ Error: ${error.message}`);
    process.exit(1);
});

