import { z } from 'zod';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { detectAiTools } from '../engine/ai-integration/detector.js';
import { safeTracked } from './safe-handler.js';
import { resolveProjectId, missingProjectIdError } from './resolve-project-id.js';
// ---------------------------------------------------------------------------
// Zod schema
// ---------------------------------------------------------------------------
export const AiEcosystemStatusSchema = {
    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.'),
};
// ---------------------------------------------------------------------------
// Health scoring
// ---------------------------------------------------------------------------
const HOME = homedir();
function hasPlanusddSection(filePath) {
    try {
        const content = readFileSync(filePath, 'utf8');
        return content.includes('planu-sdd');
    }
    catch {
        /* v8 ignore next */
        return false;
    }
}
function scoreClaudeCode(projectPath) {
    const configured = [];
    const missing = [];
    if (existsSync(join(projectPath, 'CLAUDE.md'))) {
        configured.push('CLAUDE.md');
    }
    else {
        missing.push('CLAUDE.md');
    }
    if (existsSync(join(projectPath, '.claude', 'hooks'))) {
        configured.push('hooks');
    }
    else {
        missing.push('hooks');
    }
    if (existsSync(join(projectPath, '.claude', 'skills'))) {
        configured.push('skills');
    }
    else {
        missing.push('skills');
    }
    const total = configured.length + missing.length;
    const score = total > 0 ? Math.round((configured.length / total) * 100) : 0;
    const suggestions = missing.map((m) => `Add ${m} to improve Claude Code integration`);
    return { tool: 'claude-code', score, configured, missing, suggestions };
}
function scoreCodexCli(projectPath) {
    const configured = [];
    const missing = [];
    if (existsSync(join(projectPath, 'AGENTS.md'))) {
        configured.push('AGENTS.md');
    }
    else {
        missing.push('AGENTS.md');
    }
    const codexConfig = join(HOME, '.codex', 'config.toml');
    if (existsSync(codexConfig)) {
        configured.push('.codex/config.toml');
    }
    else {
        missing.push('.codex/config.toml');
    }
    const total = configured.length + missing.length;
    const score = total > 0 ? Math.round((configured.length / total) * 100) : 0;
    return { tool: 'codex-cli', score, configured, missing, suggestions: [] };
}
function scoreGeminiCli(projectPath) {
    const configured = [];
    const missing = [];
    if (existsSync(join(projectPath, 'GEMINI.md'))) {
        configured.push('GEMINI.md');
    }
    else {
        missing.push('GEMINI.md');
    }
    const geminiSettings = join(HOME, '.gemini', 'settings.json');
    if (existsSync(geminiSettings)) {
        configured.push('.gemini/settings.json');
    }
    else {
        missing.push('.gemini/settings.json');
    }
    const total = configured.length + missing.length;
    const score = total > 0 ? Math.round((configured.length / total) * 100) : 0;
    return { tool: 'gemini-cli', score, configured, missing, suggestions: [] };
}
function scoreCursor(projectPath) {
    const configured = [];
    const missing = [];
    const suggestions = [];
    const rulesPath = join(projectPath, '.cursorrules');
    if (existsSync(rulesPath)) {
        configured.push('.cursorrules');
        if (hasPlanusddSection(rulesPath)) {
            configured.push('planu-sdd section');
        }
        else {
            missing.push('planu-sdd section');
            suggestions.push('Run sync_ai_configs to inject Planu SDD section into .cursorrules');
        }
    }
    else {
        missing.push('.cursorrules');
        suggestions.push('Run sync_ai_configs to generate .cursorrules');
    }
    const total = configured.length + missing.length;
    const score = total > 0 ? Math.round((configured.length / total) * 100) : 0;
    return { tool: 'cursor', score, configured, missing, suggestions };
}
function scoreWindsurf(projectPath) {
    const configured = [];
    const missing = [];
    const suggestions = [];
    const rulesPath = join(projectPath, '.windsurfrules');
    if (existsSync(rulesPath)) {
        configured.push('.windsurfrules');
        if (hasPlanusddSection(rulesPath)) {
            configured.push('planu-sdd section');
        }
        else {
            missing.push('planu-sdd section');
            suggestions.push('Run sync_ai_configs to inject Planu SDD section into .windsurfrules');
        }
    }
    else {
        missing.push('.windsurfrules');
        suggestions.push('Run sync_ai_configs to generate .windsurfrules');
    }
    const total = configured.length + missing.length;
    const score = total > 0 ? Math.round((configured.length / total) * 100) : 0;
    return { tool: 'windsurf', score, configured, missing, suggestions };
}
function scoreGeneric(tool) {
    return {
        tool,
        score: 50,
        configured: ['detected'],
        missing: ['planu-integration'],
        suggestions: ['No deep Planu integration available for this tool yet'],
    };
}
const SCORERS = {
    'claude-code': scoreClaudeCode,
    'codex-cli': scoreCodexCli,
    'gemini-cli': scoreGeminiCli,
    cursor: scoreCursor,
    windsurf: scoreWindsurf,
};
function scoreHealth(tool, projectPath) {
    const scorer = SCORERS[tool];
    return scorer !== undefined ? scorer(projectPath) : scoreGeneric(tool);
}
// ---------------------------------------------------------------------------
// Formatter
// ---------------------------------------------------------------------------
function formatHealth(health) {
    const lines = [];
    lines.push('# AI Ecosystem Health Report');
    lines.push('');
    lines.push(`**Overall Score**: ${health.overallScore}/100`);
    lines.push(`**Scanned At**: ${health.scannedAt}`);
    lines.push('');
    lines.push('| Tool | Score | Configured | Missing |');
    lines.push('|------|-------|-----------|---------|');
    for (const t of health.tools) {
        const configuredStr = t.configured.length > 0 ? t.configured.join(', ') : '—';
        const missingStr = t.missing.length > 0 ? t.missing.join(', ') : '—';
        lines.push(`| ${t.tool} | ${t.score}/100 | ${configuredStr} | ${missingStr} |`);
    }
    const allSuggestions = health.tools.flatMap((t) => t.suggestions);
    if (allSuggestions.length > 0) {
        lines.push('');
        lines.push('## Suggestions');
        lines.push('');
        for (const s of allSuggestions) {
            lines.push(`- ${s}`);
        }
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export function handleAiEcosystemStatus(input) {
    const scan = detectAiTools(input.projectPath);
    const detectedTools = scan.tools.filter((t) => t.detected);
    const toolHealths = detectedTools.map((t) => scoreHealth(t.name, input.projectPath));
    const overallScore = toolHealths.length > 0
        ? Math.round(toolHealths.reduce((sum, t) => sum + t.score, 0) / toolHealths.length)
        : 0;
    const health = {
        tools: toolHealths,
        overallScore,
        scannedAt: scan.scannedAt,
    };
    return Promise.resolve({ content: [{ type: 'text', text: formatHealth(health) }] });
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
export function registerAiEcosystemStatusTool(server) {
    server.registerTool('ecosystem_status', {
        description: 'Scan the AI tool ecosystem of a project and return a health report showing which AI tools are detected and how well they are configured for Planu SDD workflow.',
        inputSchema: AiEcosystemStatusSchema,
        annotations: {
            readOnlyHint: true,
            destructiveHint: false,
            title: 'AI Ecosystem Status',
        },
    }, safeTracked('ecosystem_status', async (args) => {
        const pid = resolveProjectId(args);
        if (!pid) {
            return missingProjectIdError;
        }
        return handleAiEcosystemStatus(args);
    }));
}
//# sourceMappingURL=ai-ecosystem-status.js.map