import * as fs from 'fs';
import * as path from 'path';
import { HandlerContext } from './types';
import { findBrainFiles } from '../../utils';
import { EXCLUDED_DIRS } from '../../config';

export async function applyBrainOpsActions(ctx: HandlerContext): Promise<void> {
    const { aiMessage, activeBrainDir, report } = ctx;
    let match: RegExpExecArray | null;

    // Action 7: Second Brain Knowledge (List/Read)
    const listBrainRegex = /<list_brain\s*path=['"]?([^'"]*)['"]?\s*\/?>(?:<\/list_brain>)?/gi;
    while ((match = listBrainRegex.exec(aiMessage)) !== null) {
        const relPath = match[1].trim() || '.';
        try {
            const brainDir = activeBrainDir;
            const absPath = path.join(brainDir, relPath);
            if (fs.existsSync(absPath) && fs.statSync(absPath).isDirectory()) {
                const entries = fs.readdirSync(absPath, { withFileTypes: true });
                let listing = entries
                    .filter(e => !e.name.startsWith('.') && !EXCLUDED_DIRS.has(e.name))
                    .map(e => e.isDirectory() ? `${e.name}/` : e.name)
                    .join('\n');

                if (listing.length > 5000) {
                    listing = listing.slice(0, 5000) + "\n... (truncated for context)";
                }

                report.push(`🧠 Brain Listed: ${relPath}`);
                ctx.chatHistory.push({ role: 'system', content: `[Result of list_brain ${relPath}]\n${listing}`, internal: true });
            } else {
                report.push(`❌ Brain List failed: ${relPath} not found`);
            }
        } catch (err: any) { report.push(`❌ Error Listing Brain: ${err.message}`); }
    }

    const brainRegex = /<read_brain>([\s\S]*?)<\/read_brain>/gi;
    while ((match = brainRegex.exec(aiMessage)) !== null) {
        const fileName = match[1].trim();
        try {
            const brainDir = activeBrainDir;
            const files = findBrainFiles(brainDir);
            const targetFile = files.find((f: string) => path.basename(f) === fileName || f.endsWith(fileName));

            if (targetFile && fs.existsSync(targetFile)) {
                const content = fs.readFileSync(targetFile, 'utf-8');
                report.push(`🧠 Brain Read: ${fileName}`);
                ctx.chatHistory.push({ role: 'system', content: `[Result of read_brain ${fileName}]\n\`\`\`\n${content}\n\`\`\``, internal: true });
            } else {
                report.push(`❌ Brain Read failed: ${fileName} not found in Second Brain`);
            }
        } catch (err: any) { report.push(`❌ Error Reading Brain: ${err.message}`); }
    }
}
