// @crash-shield-ignore-file — config/cache reader for Planu-controlled JSON; writer is this codebase, shape guaranteed by build/seed.
// engine/filesystem-watcher/index.ts — SPEC-329: Filesystem watcher engine
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
const HOOKS_FILE = '.planu/hooks.json';
/**
 * Returns the default hooks configuration (disabled with no hooks).
 */
export function getDefaultHooksConfig() {
    return { enabled: false, hooks: [] };
}
/**
 * Loads the hooks configuration from `.planu/hooks.json` in the given project path.
 * Returns the default config if the file does not exist.
 */
export async function loadHooksConfig(projectPath) {
    const filePath = join(projectPath, HOOKS_FILE);
    try {
        const raw = await readFile(filePath, 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return getDefaultHooksConfig();
    }
}
/**
 * Saves the hooks configuration to `.planu/hooks.json` in the given project path.
 * Creates the `.planu` directory if it does not exist.
 */
export async function saveHooksConfig(projectPath, config) {
    const dir = join(projectPath, '.planu');
    await mkdir(dir, { recursive: true });
    const filePath = join(projectPath, HOOKS_FILE);
    await writeFile(filePath, JSON.stringify(config, null, 2), 'utf-8');
}
/**
 * Converts a glob pattern to a RegExp.
 * Supports `**` (any path segments) and `*` (any characters within a segment).
 * Strategy: split on `*` boundaries to escape non-wildcard parts separately.
 */
function patternToRegex(pattern) {
    // Split by ** first, then by *
    const parts = pattern.split('**');
    const regexStr = parts
        .map((part) => {
        // Within each ** segment, handle single *
        return part
            .split('*')
            .map((segment) => segment.replace(/[.+^${}()|[\]\\]/g, '\\$&'))
            .join('[^/]*');
    })
        .join('.*');
    return new RegExp(`^${regexStr}$`);
}
/**
 * Returns true if `filePath` matches the given glob `pattern`.
 * Supports `**` and `*` wildcards.
 */
export function matchesPattern(filePath, pattern) {
    const regex = patternToRegex(pattern);
    return regex.test(filePath);
}
/**
 * Builds a trigger event for a filesystem hook match.
 */
export function buildTriggerEvent(event, filePath, hook) {
    return {
        event,
        filePath,
        timestamp: new Date().toISOString(),
        matchedPattern: hook.pattern,
        tool: hook.tool,
    };
}
/**
 * Finds all hooks in `config` that match the given event and file path,
 * and returns the result with triggered events.
 * Does NOT call any tools — pure logic only.
 */
export function processFileEvent(event, filePath, config) {
    if (!config.enabled) {
        return { triggered: 0, events: [], errors: [] };
    }
    const events = [];
    const errors = [];
    for (const hook of config.hooks) {
        if (hook.event !== event) {
            continue;
        }
        try {
            if (matchesPattern(filePath, hook.pattern)) {
                events.push(buildTriggerEvent(event, filePath, hook));
            }
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            errors.push(`Pattern "${hook.pattern}" error: ${msg}`);
        }
    }
    return { triggered: events.length, events, errors };
}
//# sourceMappingURL=index.js.map