"use strict";
/**
 * Image Analyzer Hook Utilities
 *
 * Shared helper functions for CCS-managed image hook detection and cleanup.
 *
 * @module utils/hooks/image-analyzer-hook-utils
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeCcsImageAnalyzerHooks = exports.deduplicateCcsImageAnalyzerHooks = exports.isCcsImageAnalyzerHook = void 0;
function normalizeCommand(command) {
    return command.replace(/\\/g, '/').replace(/\/+/g, '/');
}
function extractManagedHookPath(command) {
    const normalizedCommand = normalizeCommand(command);
    const exactPathMatch = normalizedCommand.match(/(?:^|["'\s])([^"'\s]*\/\.ccs\/hooks\/image-analyzer-transformer\.cjs)(?:["'\s]|$)/);
    return exactPathMatch?.[1] ?? null;
}
/**
 * Check if a hook entry is a CCS-managed image analyzer hook.
 * Matches current and legacy path variants by suffix rather than full path.
 */
function isCcsImageAnalyzerHook(hook) {
    if (hook.matcher !== 'Read')
        return false;
    const hookArray = hook.hooks;
    if (!hookArray?.[0]?.command)
        return false;
    const command = hookArray[0].command;
    if (typeof command !== 'string')
        return false;
    return extractManagedHookPath(command) !== null;
}
exports.isCcsImageAnalyzerHook = isCcsImageAnalyzerHook;
/**
 * Remove duplicate CCS-managed image hooks from settings, keeping only the first one.
 */
function deduplicateCcsImageAnalyzerHooks(settings) {
    const hooks = settings.hooks;
    if (!hooks?.PreToolUse)
        return false;
    let foundFirst = false;
    const originalLength = hooks.PreToolUse.length;
    hooks.PreToolUse = hooks.PreToolUse.filter((entry) => {
        const hook = entry;
        if (!isCcsImageAnalyzerHook(hook))
            return true;
        if (!foundFirst) {
            foundFirst = true;
            return true;
        }
        return false;
    });
    return hooks.PreToolUse.length < originalLength;
}
exports.deduplicateCcsImageAnalyzerHooks = deduplicateCcsImageAnalyzerHooks;
/**
 * Remove all CCS-managed image hooks from settings while preserving unrelated hooks.
 */
function removeCcsImageAnalyzerHooks(settings) {
    const hooks = settings.hooks;
    if (!hooks?.PreToolUse)
        return false;
    const originalLength = hooks.PreToolUse.length;
    hooks.PreToolUse = hooks.PreToolUse.filter((entry) => {
        const hook = entry;
        return !isCcsImageAnalyzerHook(hook);
    });
    if (hooks.PreToolUse.length === originalLength) {
        return false;
    }
    if (hooks.PreToolUse.length === 0) {
        delete hooks.PreToolUse;
    }
    if (Object.keys(hooks).length === 0) {
        delete settings.hooks;
    }
    return true;
}
exports.removeCcsImageAnalyzerHooks = removeCcsImageAnalyzerHooks;
//# sourceMappingURL=image-analyzer-hook-utils.js.map