/**
 * PostToolUse analytics handler — tracks Skill and Task (subagent) usage.
 *
 * Appends events to `<stateDir>/analytics/events.jsonl`.
 * Non-blocking, never throws.
 *
 * @module core/hooks/handlers/post-tool-use-analytics
 */
import * as fs from 'fs';
import * as path from 'path';
const CONTINUE = { continue: true };
function getToolInput(input) {
    return (input.tool_input ?? input.toolInput ?? {});
}
function resolveToolName(input) {
    const explicit = (input.tool_name ?? input.toolName ?? '');
    if (explicit)
        return explicit;
    // Fallback: detect from input fields
    const ti = getToolInput(input);
    if (ti.skill)
        return 'Skill';
    if (ti.subagent_type)
        return 'Task';
    return '';
}
function extractPlugin(skillName) {
    if (!skillName.includes(':'))
        return 'specweave';
    const prefix = skillName.split(':')[0];
    return prefix === 'sw' ? 'specweave' : prefix;
}
export const handle = async (input, context) => {
    const toolName = resolveToolName(input);
    const ti = getToolInput(input);
    if (toolName === 'Skill') {
        const skillName = (ti.skill ?? '');
        if (!skillName)
            return CONTINUE;
        const plugin = extractPlugin(skillName);
        const event = {
            timestamp: context.timestamp,
            type: 'skill',
            name: skillName,
            success: true,
            plugin,
        };
        appendEvent(context.stateDir, event);
        return CONTINUE;
    }
    if (toolName === 'Task') {
        const agentType = (ti.subagent_type ?? 'general');
        const event = {
            timestamp: context.timestamp,
            type: 'agent',
            name: agentType,
            success: true,
            plugin: 'specweave',
        };
        appendEvent(context.stateDir, event);
        return CONTINUE;
    }
    return CONTINUE;
};
function appendEvent(stateDir, event) {
    try {
        const analyticsDir = path.join(stateDir, 'analytics');
        fs.mkdirSync(analyticsDir, { recursive: true });
        fs.appendFileSync(path.join(analyticsDir, 'events.jsonl'), JSON.stringify(event) + '\n');
    }
    catch {
        // Never throw from analytics
    }
}
//# sourceMappingURL=post-tool-use-analytics.js.map