// @crash-shield-ignore-file — config/cache reader for Planu-controlled JSON; writer is this codebase, shape guaranteed by build/seed.
// Planu — Ecosystem detector engine (SPEC-374)
// Pure functions to detect token optimization tools (RTK, Headroom)
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
async function readJsonFile(filePath) {
    try {
        const content = await readFile(filePath, 'utf-8');
        return JSON.parse(content);
    }
    catch {
        return null;
    }
}
export async function detectRtkHooks(projectPath) {
    const settingsPath = join(projectPath, '.claude', 'settings.json');
    const settings = await readJsonFile(settingsPath);
    if (!settings?.hooks?.PreToolUse) {
        return 0;
    }
    return settings.hooks.PreToolUse.filter((hook) => {
        const hooksArr = hook.hooks ?? [];
        return hooksArr.some((h) => typeof h === 'string' && h.toLowerCase().includes('rtk'));
    }).length;
}
export async function detectHeadroomPackage(projectPath) {
    const pkgPath = join(projectPath, 'package.json');
    const pkg = await readJsonFile(pkgPath);
    if (!pkg) {
        return { installed: false };
    }
    const allDeps = {
        ...(pkg.devDependencies ?? {}),
        ...(pkg.dependencies ?? {}),
    };
    const headroom = allDeps.headroom;
    const headroomCli = allDeps['@headroom/cli'];
    const version = headroom ?? headroomCli;
    if (version !== undefined) {
        return { installed: true, version };
    }
    return { installed: false };
}
export async function detectRtkPackage(projectPath) {
    const pkgPath = join(projectPath, 'package.json');
    const pkg = await readJsonFile(pkgPath);
    if (!pkg) {
        return { installed: false };
    }
    const allDeps = {
        ...(pkg.devDependencies ?? {}),
        ...(pkg.dependencies ?? {}),
    };
    const rtk = allDeps.rtk;
    const rtkCli = allDeps['@rtk/cli'];
    const version = rtk ?? rtkCli;
    if (version !== undefined) {
        return { installed: true, version };
    }
    return { installed: false };
}
export async function getTokenOptimizerStatus(projectPath) {
    const [rtkPkg, headroomPkg, rtkHooks] = await Promise.all([
        detectRtkPackage(projectPath),
        detectHeadroomPackage(projectPath),
        detectRtkHooks(projectPath),
    ]);
    return {
        rtk: {
            installed: rtkPkg.installed,
            version: rtkPkg.version,
            hooksConfigured: rtkHooks,
        },
        headroom: {
            installed: headroomPkg.installed,
            version: headroomPkg.version,
        },
    };
}
export async function buildTokenOptimizerRecommendations(projectPath) {
    const status = await getTokenOptimizerStatus(projectPath);
    const recommendations = [];
    if (!status.rtk.installed) {
        recommendations.push({
            tool: 'rtk',
            installed: false,
            reason: 'RTK (Response Token Killer) filters verbose Claude output via PreToolUse hooks, reducing token usage by 30-60% on large codebases.',
            installCommand: 'npm install --save-dev rtk',
            configExample: JSON.stringify({
                hooks: {
                    PreToolUse: [
                        {
                            matcher: 'Bash',
                            hooks: ['npx rtk filter'],
                        },
                    ],
                },
            }, null, 2),
        });
    }
    else {
        recommendations.push({
            tool: 'rtk',
            installed: true,
            reason: `RTK is installed (${status.rtk.version ?? 'unknown version'}). ${status.rtk.hooksConfigured === 0
                ? 'No PreToolUse hooks configured yet — add hooks to .claude/settings.json to activate filtering.'
                : `${String(status.rtk.hooksConfigured)} PreToolUse hook(s) configured.`}`,
            installCommand: 'npm install --save-dev rtk',
        });
    }
    if (!status.headroom.installed) {
        recommendations.push({
            tool: 'headroom',
            installed: false,
            reason: 'Headroom monitors your context window usage in real-time and warns before you hit the limit, preventing lost work.',
            installCommand: 'npm install --save-dev headroom',
        });
    }
    else {
        recommendations.push({
            tool: 'headroom',
            installed: true,
            reason: `Headroom is installed (${status.headroom.version ?? 'unknown version'}).`,
            installCommand: 'npm install --save-dev headroom',
        });
    }
    return recommendations;
}
//# sourceMappingURL=ecosystem-detector.js.map