import { z } from 'zod';
import { safeLicensed, safeTracked } from './safe-handler.js';
import { SpecIdSchema } from './schemas/index.js';
import { onAutopilotEvent } from '../engine/autopilot/event-bus.js';
import { dispatchSquadForPhase } from '../engine/agent-squad/dispatcher.js';
import { getSquadConfig, setAgentEnabled, getSpecRunHistory, getSquadRuns, } from '../storage/agent-squad-store.js';
import { hashProjectPath } from '../storage/base-store.js';
// ---------------------------------------------------------------------------
// Autopilot handlers (registered at startup, not MCP tools)
// ---------------------------------------------------------------------------
export function registerAgentSquadHandlers() {
    onAutopilotEvent('spec:status:implementing', (event) => {
        if (!event.specId) {
            return;
        }
        const ctx = {
            specId: event.specId,
            projectId: event.projectId,
            projectPath: event.projectPath,
            specTags: event.payload?.tags ?? [],
            specType: event.payload?.type ?? 'feature',
            specScope: event.payload?.scope ?? 'feature',
        };
        void dispatchSquadForPhase(ctx, 'pre-implementation').catch((err) => {
            console.error('[agent-squad] dispatch error (pre-implementation):', err);
        });
        void dispatchSquadForPhase(ctx, 'implementation').catch((err) => {
            console.error('[agent-squad] dispatch error (implementation):', err);
        });
    });
    onAutopilotEvent('spec:status:review', (event) => {
        if (!event.specId) {
            return;
        }
        const ctx = {
            specId: event.specId,
            projectId: event.projectId,
            projectPath: event.projectPath,
            specTags: event.payload?.tags ?? [],
            specType: event.payload?.type ?? 'feature',
            specScope: event.payload?.scope ?? 'feature',
        };
        void dispatchSquadForPhase(ctx, 'review').catch((err) => {
            console.error('[agent-squad] dispatch error (review):', err);
        });
    });
    onAutopilotEvent('spec:status:done', (event) => {
        if (!event.specId) {
            return;
        }
        const ctx = {
            specId: event.specId,
            projectId: event.projectId,
            projectPath: event.projectPath,
            specTags: event.payload?.tags ?? [],
            specType: event.payload?.type ?? 'feature',
            specScope: event.payload?.scope ?? 'feature',
        };
        void dispatchSquadForPhase(ctx, 'post-implementation').catch((err) => {
            console.error('[agent-squad] dispatch error (post-implementation):', err);
        });
    });
}
// ---------------------------------------------------------------------------
// MCP tools
// ---------------------------------------------------------------------------
export function registerAgentSquadTools(server) {
    server.registerTool('configure_squad', {
        description: 'Enable or disable a specific specialist agent for a project. ' +
            'Overrides the default enabled state in agent-registry.json without modifying it. ' +
            'Valid agentIds: figma-agent, developer-agent, code-reviewer-agent, ' +
            'security-reviewer-agent, qa-agent, arbiter-agent, docs-agent.',
        inputSchema: {
            projectPath: z.string().min(1).max(4096).describe('Absolute path to the project root.'),
            agentId: z
                .string()
                .min(1)
                .max(100)
                .describe('ID of the specialist agent to configure. Valid values: figma-agent, ' +
                'developer-agent, code-reviewer-agent, security-reviewer-agent, ' +
                'qa-agent, arbiter-agent, docs-agent.'),
            enabled: z
                .boolean()
                .describe('Set to true to enable the agent, false to disable it for this project.'),
        },
    }, safeLicensed('configure_squad', async (args) => {
        const { projectPath, agentId, enabled } = args;
        const projectId = hashProjectPath(projectPath);
        await setAgentEnabled(projectId, agentId, enabled);
        return {
            content: [
                {
                    type: 'text',
                    text: `Agent ${agentId} ${enabled ? 'enabled' : 'disabled'} for this project.`,
                },
            ],
        };
    }));
    server.registerTool('squad_status', {
        description: 'Show all registered specialist agents for a project, ' +
            'whether they are enabled, and their last run result per spec. ' +
            'Reflects any per-project overrides set via configure_squad.',
        inputSchema: {
            projectPath: z.string().min(1).max(4096).describe('Absolute path to the project root.'),
        },
    }, safeTracked('squad_status', async (args) => {
        const { projectPath } = args;
        const projectId = hashProjectPath(projectPath);
        const [config, runs] = await Promise.all([
            getSquadConfig(projectId),
            getSquadRuns(projectId),
        ]);
        const overrideMap = new Map(config.overrides.map((o) => [o.agentId, o.enabled]));
        const recentByAgent = new Map();
        for (const history of runs) {
            const last = history.runs.at(-1);
            if (last) {
                const existing = recentByAgent.get(last.agentId);
                if (!existing || last.triggeredAt > existing) {
                    recentByAgent.set(last.agentId, `${last.verdict} (${history.specId})`);
                }
            }
        }
        const agents = [
            'figma-agent',
            'developer-agent',
            'code-reviewer-agent',
            'security-reviewer-agent',
            'qa-agent',
            'arbiter-agent',
            'docs-agent',
        ];
        const lines = agents.map((id) => {
            const enabled = overrideMap.get(id) ?? true;
            const last = recentByAgent.get(id) ?? 'no runs yet';
            return `${enabled ? '✅' : '❌'} ${id} — last: ${last}`;
        });
        return {
            content: [{ type: 'text', text: lines.join('\n') }],
        };
    }));
    server.registerTool('agent_run_history', {
        description: 'Show the history of specialist agent runs for a specific spec: ' +
            'which agents ran, their verdict, and when.',
        inputSchema: {
            projectPath: z.string().min(1).max(4096).describe('Absolute path to the project root.'),
            specId: SpecIdSchema.describe('Spec ID to query (e.g. SPEC-550).'),
        },
    }, safeTracked('agent_run_history', async (args) => {
        const { projectPath, specId } = args;
        const projectId = hashProjectPath(projectPath);
        const history = await getSpecRunHistory(projectId, specId);
        if (!history || history.runs.length === 0) {
            return {
                content: [{ type: 'text', text: `No agent runs recorded for ${specId}.` }],
            };
        }
        const lines = history.runs.map((r) => `[${r.triggeredAt}] ${r.agentId} (${r.phase}) — ${r.verdict}: ${r.summary}`);
        return {
            content: [{ type: 'text', text: lines.join('\n') }],
        };
    }));
}
//# sourceMappingURL=register-agent-squad-tools.js.map