// packages/plugin-awf/src/commands/doctor.ts
// AWF Doctor Command - Diagnose IDE configurations
import * as fs from "node:fs";
import * as path from "node:path";
import pc from "picocolors";
import * as prompts from "@clack/prompts";
import { IDE_REGISTRY, getIDEByValue } from "../constants/ides.js";
export const doctorFlags = {
    ide: {
        type: "string",
        description: "Check specific IDE only",
        alias: "i",
    },
    verbose: {
        type: "boolean",
        description: "Show detailed diagnostics",
        alias: "V",
        default: false,
    },
};
export async function doctorCommand(args, flags) {
    prompts.intro(pc.cyan("🩺 DOMYH Doctor"));
    const cwd = process.cwd();
    const verbose = flags.verbose;
    const specificIde = (args[0] || flags.ide);
    // Detect installed IDEs
    const installedIDEs = [];
    for (const ideConfig of IDE_REGISTRY) {
        const ruleDir = path.join(cwd, ideConfig.rulePath);
        const configFilePath = ideConfig.configFile ? path.join(cwd, ideConfig.configFile) : null;
        if (fs.existsSync(ruleDir) || (configFilePath && fs.existsSync(configFilePath))) {
            installedIDEs.push(ideConfig.value);
        }
    }
    if (installedIDEs.length === 0) {
        console.log(pc.yellow("\n⚠️ No IDE configurations found"));
        console.log(pc.dim("Run: nock awf install to set up IDE configurations"));
        prompts.outro("No configurations to diagnose");
        return;
    }
    // Filter if specific IDE requested
    const idesToCheck = specificIde
        ? installedIDEs.filter(i => i === specificIde)
        : installedIDEs;
    if (specificIde && idesToCheck.length === 0) {
        console.log(pc.yellow(`IDE "${specificIde}" not configured`));
        return;
    }
    // Diagnose each IDE
    console.log();
    let totalTokens = 0;
    let totalFiles = 0;
    for (const ideKey of idesToCheck) {
        const ideConfig = getIDEByValue(ideKey);
        if (!ideConfig)
            continue;
        const ruleDir = path.join(cwd, ideConfig.rulePath);
        console.log(pc.bold(`📁 ${ideConfig.displayName}`));
        console.log(`   Path: ${pc.dim(ideConfig.rulePath)}`);
        if (fs.existsSync(ruleDir)) {
            try {
                const files = fs.readdirSync(ruleDir).filter(f => !f.startsWith('.'));
                console.log(`   Files: ${pc.cyan(files.length.toString())}`);
                totalFiles += files.length;
                if (verbose && files.length > 0) {
                    console.log(`   ${pc.dim("Load order:")}`);
                    for (const file of files.sort().slice(0, 5)) {
                        const stats = fs.statSync(path.join(ruleDir, file));
                        const tokens = Math.round(stats.size / 4); // Approximate
                        totalTokens += tokens;
                        console.log(`     ${pc.dim("→")} ${file} ${pc.dim(`~${tokens}t`)}`);
                    }
                    if (files.length > 5) {
                        console.log(`     ${pc.dim(`... and ${files.length - 5} more`)}`);
                    }
                }
            }
            catch {
                console.log(`   ${pc.red("Error reading directory")}`);
            }
        }
        else if (ideConfig.configFile && fs.existsSync(path.join(cwd, ideConfig.configFile))) {
            console.log(`   Config: ${pc.green("✔")} ${ideConfig.configFile}`);
            totalFiles++;
        }
        console.log(`   Status: ${pc.green("✔ OK")}`);
        console.log();
    }
    // Summary
    console.log(pc.bold("Summary:"));
    console.log(`  IDEs detected: ${pc.cyan(idesToCheck.length.toString())}`);
    console.log(`  Total files: ${pc.cyan(totalFiles.toString())}`);
    if (verbose) {
        console.log(`  Est. tokens: ${pc.yellow(`~${totalTokens}`)}`);
    }
    prompts.outro(pc.green("Doctor complete!"));
}
