import { z } from 'zod';
import { detectAiTools } from '../engine/ai-integration/detector.js';
import { generateConfigsForDetectedTools } from '../engine/ai-integration/universal-config-generator.js';
import { safeTracked } from './safe-handler.js';
import { resolveProjectId, missingProjectIdError } from './resolve-project-id.js';
// ---------------------------------------------------------------------------
// Zod schema
// ---------------------------------------------------------------------------
export const SyncAiConfigsSchema = {
    projectPath: z
        .string()
        .max(4096)
        .optional()
        .describe('Absolute path to the project root. Derives projectId automatically.'),
    projectId: z.string().max(500).optional().describe('Project ID hash. Prefer projectPath.'),
    force: z.boolean().optional().describe('Overwrite existing configs'),
};
// ---------------------------------------------------------------------------
// Formatter
// ---------------------------------------------------------------------------
function formatSyncResults(results, projectPath) {
    const lines = [];
    lines.push('# AI Config Sync Results');
    lines.push('');
    lines.push(`**Project**: ${projectPath}`);
    lines.push('');
    const generated = results.filter((r) => !r.skipped && r.filesGenerated.length > 0);
    const skipped = results.filter((r) => r.skipped);
    const errored = results.filter((r) => !r.skipped && r.filesGenerated.length === 0 && r.reason);
    if (generated.length > 0) {
        lines.push('## Files Updated');
        lines.push('');
        for (const r of generated) {
            for (const f of r.filesGenerated) {
                lines.push(`- \`${f}\` (${r.tool})`);
            }
        }
        lines.push('');
    }
    if (skipped.length > 0) {
        lines.push('## Skipped');
        lines.push('');
        for (const r of skipped) {
            lines.push(`- **${r.tool}**: ${r.reason ?? 'No generator'}`);
        }
        lines.push('');
    }
    if (errored.length > 0) {
        lines.push('## Errors');
        lines.push('');
        for (const r of errored) {
            lines.push(`- **${r.tool}**: ${r.reason ?? 'Unknown error'}`);
        }
        lines.push('');
    }
    if (generated.length === 0 && errored.length === 0) {
        lines.push('No configs were updated (no supported tools detected or all skipped).');
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export function handleSyncAiConfigs(input) {
    const scan = detectAiTools(input.projectPath);
    const detectedNames = scan.tools.filter((t) => t.detected).map((t) => t.name);
    const results = generateConfigsForDetectedTools({
        projectPath: input.projectPath,
        projectName: input.projectPath.split('/').pop() ?? 'project',
        stack: [],
        approvedSpecs: [],
        detectedTools: detectedNames,
    });
    const text = formatSyncResults(results, input.projectPath);
    return Promise.resolve({ content: [{ type: 'text', text }] });
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
export function registerSyncAiConfigsTool(server) {
    server.registerTool('sync_ai_configs', {
        description: 'Detect installed AI coding tools and synchronize their configuration files with the Planu SDD workflow. Generates .cursorrules, .windsurfrules, .aider.conf.yml, etc. for detected tools.',
        inputSchema: SyncAiConfigsSchema,
        annotations: {
            readOnlyHint: false,
            destructiveHint: false,
            title: 'Sync AI Configs',
        },
    }, safeTracked('sync_ai_configs', async (args) => {
        const pid = resolveProjectId(args);
        if (!pid) {
            return missingProjectIdError;
        }
        return handleSyncAiConfigs(args);
    }));
}
//# sourceMappingURL=sync-ai-configs.js.map