'use strict';

/**
 * Integration test: poll-fallback
 *
 * Verifies that StatusWatcher detects file changes via the polling fallback
 * (not just fs.watch). Creates a temp JSONL file, initializes a StatusWatcher,
 * appends a line, and asserts the 'session-update' event fires within 1000ms.
 */

var describe = require('node:test').describe;
var it = require('node:test').it;
var beforeEach = require('node:test').beforeEach;
var afterEach = require('node:test').afterEach;
var assert = require('node:assert/strict');
var fs = require('fs');
var path = require('path');
var os = require('os');

var StatusWatcher = require('../../src/status-watcher').StatusWatcher;

function createTmpDir() {
  return fs.mkdtempSync(path.join(os.tmpdir(), 'poll-fallback-test-'));
}

describe('StatusWatcher poll fallback', function () {
  var tmpDir;
  var watcher;

  beforeEach(function () {
    tmpDir = createTmpDir();
  });

  afterEach(function () {
    if (watcher) {
      watcher.stop();
      watcher = null;
    }
    try {
      fs.rmSync(tmpDir, { recursive: true, force: true });
    } catch (_e) {
      /* ignore */
    }
  });

  it('emits session-update within 1000ms when a line is appended to the JSONL file', function (t, done) {
    var transcriptFile = path.join(tmpDir, 'test-session.jsonl');
    fs.writeFileSync(transcriptFile, '');

    watcher = new StatusWatcher({ transcriptDir: tmpDir, idleTimeoutS: 600 });

    // Use a saved offset of 0 so we read from beginning
    watcher.addSession('test:poll', transcriptFile, { lastOffset: 0 });

    var timer = setTimeout(function () {
      done(new Error('session-update event not received within 1000ms'));
    }, 1000);

    watcher.once('session-update', function (sessionKey) {
      clearTimeout(timer);
      assert.equal(sessionKey, 'test:poll');
      done();
    });

    // Append a valid JSONL line after a short delay to allow watcher setup
    setTimeout(function () {
      var record = {
        type: 'message',
        message: {
          role: 'assistant',
          content: [{ type: 'text', text: 'Poll fallback test line' }],
        },
      };
      fs.appendFileSync(transcriptFile, JSON.stringify(record) + '\n');
    }, 100);
  });
});
