import * as fs from 'fs';
import { validatePath } from '../../security';
import { FileSystemError } from '../../core/errors';
import { HandlerContext } from './types';

export async function applyFileDeleteReadActions(ctx: HandlerContext): Promise<void> {
    const { aiMessage, rootPath, report } = ctx;
    let match;

    // Action 3: Delete File
    const deleteRegex = /<delete_file\s+path=['"]?([^'"]+)['"]?\s*\/?>(?:<\/delete_file>)?/gi;
    while ((match = deleteRegex.exec(aiMessage)) !== null) {
        const relPath = match[1].trim();
        try {
            const absPath = validatePath(rootPath, relPath);
            if (fs.existsSync(absPath)) {
                await ctx.transactionManager.record(absPath);
                fs.unlinkSync(absPath);
                report.push(`🗑 Deleted: ${relPath}`);
            } else {
                report.push(`⚠️ Delete failed: ${relPath} not found`);
            }
        } catch (err: any) {
            throw new FileSystemError(`Failed to delete file ${relPath}: ${err.message}`, relPath, err);
        }
    }

    // Action 4: Read File (Non-state-changing, no transaction record needed)
    const readRegex = /<read_file\s+path=['"]?([^'"]+)['"]?\s*\/?>(?:<\/read_file>)?/gi;
    while ((match = readRegex.exec(aiMessage)) !== null) {
        const relPath = match[1].trim();
        try {
            const absPath = validatePath(rootPath, relPath);
            if (fs.existsSync(absPath)) {
                const content = fs.readFileSync(absPath, 'utf-8');
                const preview = content.length > 8000 ? content.slice(0, 8000) + "\n... (truncated)" : content;
                report.push(`📖 Read: ${relPath}`);
                ctx.chatHistory.push({ role: 'system', content: `[Result of read_file ${relPath}]\n\`\`\`\n${preview}\n\`\`\``, internal: true });
            } else {
                report.push(`❌ Read failed: ${relPath} not found`);
            }
        } catch (err: any) { report.push(`❌ Error Reading ${relPath}: ${err.message}`); }
    }
}
