"use strict";
/**
 * Dual-path file watcher with poll fallback.
 *
 * Used by the wizard agent runner to surface the canonical
 * `<installDir>/.amplitude/{events,dashboard}.json` files and their
 * legacy `.amplitude-events.json` / `.amplitude-dashboard.json` mirrors
 * (which bundled context-hub integration skills still write). Watching
 * BOTH paths keeps the UI fed regardless of which path the agent ends
 * up touching first.
 *
 * Why this lives in its own module:
 *   - The previous inline implementation in `agent-interface.ts` stored
 *     a single watcher per cleanup variable and used `??` to choose
 *     between two `fs.watch` handles. When both paths existed, only one
 *     handle landed in cleanup state — the other leaked a file
 *     descriptor for the duration of the process. This module exposes a
 *     `dispose()` that closes every handle it ever created.
 *   - Splitting it out makes the cleanup contract testable without
 *     spinning up the full `runAgent` flow.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.startDualPathWatcher = startDualPathWatcher;
const fs = __importStar(require("node:fs"));
/**
 * Start watching both `canonicalPath` and `legacyPath` for changes. If
 * neither file exists yet, falls back to polling at `pollMs` cadence
 * until at least one appears, then attaches a watcher and stops polling.
 *
 * Each path is attached at most once — partial success (one path
 * appears before the other) doesn't leak watcher handles when the
 * second path eventually appears, because the helper deduplicates.
 *
 * Calling `dispose()` closes every watcher and clears any pending poll.
 */
function startDualPathWatcher(opts) {
    const watch = opts.watch ?? defaultWatch;
    const setIntervalFn = opts.setInterval ?? globalThis.setInterval;
    const clearIntervalFn = opts.clearInterval ?? globalThis.clearInterval;
    const pollMs = opts.pollMs ?? 1000;
    const handles = [];
    const attached = new Set();
    let pollHandle;
    let disposed = false;
    /**
     * Returns `'newly-attached'` only when this call actually attached a
     * watcher. The caller uses that to decide whether `onChange` should
     * fire — distinguishing a fresh attach from "already attached" or
     * "still unavailable" lets us avoid duplicate UI updates.
     */
    const tryAttach = (target) => {
        if (disposed)
            return 'miss';
        if (attached.has(target))
            return 'already';
        const w = watch(target, opts.onChange);
        if (!w)
            return 'miss';
        attached.add(target);
        handles.push(w);
        return 'newly-attached';
    };
    const allAttached = () => attached.has(opts.canonicalPath) && attached.has(opts.legacyPath);
    /**
     * Start polling iff we haven't already AND one or both paths are still
     * missing. Stops polling once both are attached.
     *
     * Critical: polling continues even after one path attaches. The
     * previous implementation stopped polling as soon as ANY path
     * attached, which broke the dashboard flow — bundled context-hub
     * skills only ever write the legacy path, so when canonical existed
     * at startup (e.g. from a prior run) the wizard latched onto it and
     * silently missed the agent's eventual write to the legacy path.
     */
    const startPolling = () => {
        if (pollHandle !== undefined || disposed || allAttached())
            return;
        pollHandle = setIntervalFn(() => {
            const a = tryAttach(opts.canonicalPath);
            const b = tryAttach(opts.legacyPath);
            if (a === 'newly-attached' || b === 'newly-attached') {
                opts.onChange();
            }
            if (allAttached()) {
                clearIntervalFn(pollHandle);
                pollHandle = undefined;
            }
        }, pollMs);
    };
    const initialCanonical = tryAttach(opts.canonicalPath);
    const initialLegacy = tryAttach(opts.legacyPath);
    if (initialCanonical === 'newly-attached' ||
        initialLegacy === 'newly-attached') {
        opts.onChange();
    }
    if (!allAttached())
        startPolling();
    return {
        watchers: () => handles,
        isWatching: () => handles.length > 0,
        dispose: () => {
            disposed = true;
            for (const h of handles) {
                try {
                    h.close();
                }
                catch {
                    // Best-effort — close-after-rename can throw on some platforms.
                }
            }
            handles.length = 0;
            attached.clear();
            if (pollHandle !== undefined) {
                clearIntervalFn(pollHandle);
                pollHandle = undefined;
            }
        },
    };
}
function defaultWatch(target, listener) {
    try {
        return fs.watch(target, listener);
    }
    catch {
        return undefined;
    }
}
