"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranscriptWatcher = void 0;
const node_fs_1 = require("node:fs");
const transcript_1 = require("./transcript");
const DEBOUNCE_MS = 250;
const POLL_INTERVAL_MS = 500;
class TranscriptWatcher {
    sessionId;
    cwd;
    onUpdate;
    watcher = null;
    polling = false;
    timer = null;
    lastSize = 0;
    stopped = false;
    filePath;
    constructor(sessionId, cwd, onUpdate) {
        this.sessionId = sessionId;
        this.cwd = cwd;
        this.onUpdate = onUpdate;
        this.filePath = (0, transcript_1.getTranscriptPath)(sessionId, cwd);
    }
    start() {
        if ((0, node_fs_1.existsSync)(this.filePath)) {
            this.watchWithInotify();
        }
        else {
            this.watchWithPoll();
        }
    }
    async stop() {
        this.stopped = true;
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
        if (this.watcher) {
            this.watcher.close();
            this.watcher = null;
        }
        if (this.polling) {
            (0, node_fs_1.unwatchFile)(this.filePath);
            this.polling = false;
        }
        await this.reload();
    }
    watchWithInotify() {
        try {
            this.watcher = (0, node_fs_1.watch)(this.filePath, () => this.scheduleReload());
        }
        catch {
            this.watchWithPoll();
        }
    }
    watchWithPoll() {
        this.polling = true;
        (0, node_fs_1.watchFile)(this.filePath, { interval: POLL_INTERVAL_MS }, () => {
            if (this.stopped)
                return;
            if (!this.watcher && (0, node_fs_1.existsSync)(this.filePath)) {
                (0, node_fs_1.unwatchFile)(this.filePath);
                this.polling = false;
                this.watchWithInotify();
            }
            this.scheduleReload();
        });
    }
    scheduleReload() {
        if (this.stopped)
            return;
        if (this.timer)
            clearTimeout(this.timer);
        this.timer = setTimeout(() => this.reload(), DEBOUNCE_MS);
    }
    async reload() {
        try {
            const result = await (0, transcript_1.loadTranscript)(this.sessionId, this.cwd, { tailLines: 150 });
            if (result.totalSize !== this.lastSize) {
                this.lastSize = result.totalSize;
                this.onUpdate(result.messages, result.lastUsage);
            }
        }
        catch {
            if (!this.stopped) {
                this.timer = setTimeout(() => this.reload(), 100);
            }
        }
    }
}
exports.TranscriptWatcher = TranscriptWatcher;
