"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.watchCwd = watchCwd;
const node_fs_1 = require("node:fs");
const watches = new Map();
const DEBOUNCE_MS = 500;
const IGNORE_RE = /(?:^|[\\/])(?:\.git[\\/](?!HEAD$|refs[\\/])|\.next[\\/]|node_modules[\\/])/;
function startWatch(cwd) {
    let timer = null;
    const entry = {
        watcher: (0, node_fs_1.watch)(cwd, { recursive: true }, (_event, filename) => {
            if (filename && IGNORE_RE.test(filename))
                return;
            if (timer)
                return;
            timer = setTimeout(() => {
                timer = null;
                for (const fn of entry.listeners)
                    fn();
            }, DEBOUNCE_MS);
        }),
        listeners: new Set(),
    };
    entry.watcher.on("error", (err) => {
        console.log(`[fs-watcher] error on ${cwd}: ${err.message}`);
        cleanupWatch(cwd);
    });
    return entry;
}
function cleanupWatch(cwd) {
    const entry = watches.get(cwd);
    if (!entry)
        return;
    entry.watcher.close();
    watches.delete(cwd);
}
function watchCwd(cwd, listener) {
    let entry = watches.get(cwd);
    if (!entry) {
        entry = startWatch(cwd);
        watches.set(cwd, entry);
    }
    entry.listeners.add(listener);
    return () => {
        entry.listeners.delete(listener);
        if (entry.listeners.size === 0) {
            cleanupWatch(cwd);
        }
    };
}
