// tools/configure-workers-handler.ts — Handler for configure_workers tool (SPEC-078 AC-12)
import { readFile, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { getWorkerEngine } from '../engine/workers/index.js';
import { updateOverride } from '../storage/worker-store.js';
import { compactResult, formatKeyValue } from './output-formatter.js';
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export async function handleConfigureWorkers(args) {
    const engine = getWorkerEngine();
    const definitions = engine.getWorkerDefinitions();
    const worker = definitions.find((w) => w.name === args.workerName);
    if (!worker) {
        const available = definitions.map((w) => w.name).join(', ');
        return {
            content: [
                {
                    type: 'text',
                    text: `Worker "${args.workerName}" not found. Available: ${available}`,
                },
            ],
            isError: true,
        };
    }
    const override = {};
    let description = '';
    switch (args.action) {
        case 'enable':
            override.enabled = true;
            description = `Enabled worker "${args.workerName}"`;
            break;
        case 'disable':
            override.enabled = false;
            description = `Disabled worker "${args.workerName}"`;
            break;
        case 'set-cooldown': {
            if (typeof args.value !== 'number' || args.value < 0) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: 'set-cooldown requires a non-negative number value (milliseconds).',
                        },
                    ],
                    isError: true,
                };
            }
            override.cooldownMs = args.value;
            description = `Set cooldown for "${args.workerName}" to ${String(args.value)}ms`;
            break;
        }
        case 'set-priority': {
            if (typeof args.value !== 'number' || args.value < 1 || args.value > 10) {
                return {
                    content: [{ type: 'text', text: 'set-priority requires a number between 1 and 10.' }],
                    isError: true,
                };
            }
            override.priority = args.value;
            description = `Set priority for "${args.workerName}" to ${String(args.value)}`;
            break;
        }
        case 'add-pattern': {
            if (typeof args.value !== 'string' || args.value.length === 0) {
                return {
                    content: [{ type: 'text', text: 'add-pattern requires a string value (glob pattern).' }],
                    isError: true,
                };
            }
            const currentPatterns = worker.trigger.patterns ?? [];
            if (currentPatterns.includes(args.value)) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `Pattern "${args.value}" already exists for "${args.workerName}".`,
                        },
                    ],
                };
            }
            override.triggerPatterns = [...currentPatterns, args.value];
            description = `Added pattern "${args.value}" to "${args.workerName}"`;
            break;
        }
        case 'remove-pattern': {
            if (typeof args.value !== 'string' || args.value.length === 0) {
                return {
                    content: [
                        { type: 'text', text: 'remove-pattern requires a string value (glob pattern).' },
                    ],
                    isError: true,
                };
            }
            const patterns = worker.trigger.patterns ?? [];
            if (!patterns.includes(args.value)) {
                return {
                    content: [
                        { type: 'text', text: `Pattern "${args.value}" not found in "${args.workerName}".` },
                    ],
                    isError: true,
                };
            }
            override.triggerPatterns = patterns.filter((p) => p !== args.value);
            description = `Removed pattern "${args.value}" from "${args.workerName}"`;
            break;
        }
        case 'enable-auto-memory': {
            return await handleEnableWorkerAutoMemory(args.workerName, args.projectId);
        }
    }
    // Apply to engine
    engine.applyOverride(args.workerName, override);
    // Persist to storage
    await updateOverride(args.projectId, args.workerName, override);
    return {
        content: [
            { type: 'text', text: `${description}.\nConfiguration saved for project ${args.projectId}.` },
        ],
    };
}
// ---------------------------------------------------------------------------
// enable-auto-memory helper
// ---------------------------------------------------------------------------
async function handleEnableWorkerAutoMemory(workerName, projectId) {
    // Search for agent file in .claude/agents/
    const agentsDirCandidates = [
        join(process.cwd(), '.claude', 'agents', `${workerName}.md`),
        join(process.cwd(), '.claude', 'agents', `${workerName.toLowerCase()}.md`),
    ];
    const agentFile = agentsDirCandidates.find((p) => existsSync(p));
    if (!agentFile) {
        // List available agents for helpful error message
        const agentsDir = join(process.cwd(), '.claude', 'agents');
        let available = '(none found)';
        try {
            const { readdir } = await import('node:fs/promises');
            const entries = await readdir(agentsDir);
            const mdFiles = entries.filter((e) => e.endsWith('.md')).map((e) => e.replace(/\.md$/, ''));
            if (mdFiles.length > 0) {
                available = mdFiles.join(', ');
            }
        }
        catch {
            // agentsDir may not exist
        }
        return {
            content: [
                {
                    type: 'text',
                    text: `Agent file for "${workerName}" not found in .claude/agents/. Available agents: ${available}`,
                },
            ],
            isError: true,
        };
    }
    const raw = await readFile(agentFile, 'utf-8');
    // Parse YAML frontmatter manually: split by ---
    const parts = raw.split('---');
    if (parts.length < 3) {
        // No frontmatter block — prepend a minimal one
        const newContent = `---\nautoMemory: true\n---\n${raw}`;
        await writeFile(agentFile, newContent, 'utf-8');
    }
    else {
        const frontmatter = parts[1] ?? '';
        const body = parts.slice(2).join('---');
        // Check if autoMemory already set
        if (/^autoMemory:/m.test(frontmatter)) {
            // Replace existing value
            const updatedFm = frontmatter.replace(/^autoMemory:.*$/m, 'autoMemory: true');
            await writeFile(agentFile, `---${updatedFm}---${body}`, 'utf-8');
        }
        else {
            // Append to frontmatter
            const updatedFm = frontmatter.trimEnd() + '\nautoMemory: true\n';
            await writeFile(agentFile, `---${updatedFm}---${body}`, 'utf-8');
        }
    }
    const memoryPath = `~/.claude/projects/<project>/memory/agents/${workerName}/`;
    return compactResult(formatKeyValue({
        action: 'enable-auto-memory',
        workerName,
        projectId,
        agentFile,
        memoryPath,
        message: `Auto-memory enabled for agent "${workerName}". Memory will accumulate at ${memoryPath}`,
    }));
}
//# sourceMappingURL=configure-workers-handler.js.map