import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import type { Rules } from '@pixeloffice/core';
import { memoryLogger, watchRules } from '../src/index.ts';

const RULES = (agentDwell: string) => `
dwell: { agent: ${agentDwell}, human: 60s }
human: { online: [own_seat], meeting: [meeting_room], offline: [exit] }
agent: { working: ["zone:coworking"], idle: ["zone:lounge"], needs_input: [current_work_seat], offline: [exit] }
`;

describe('watchRules', () => {
  it('валидная правка применяется, невалидная — лог ошибки и прежние правила', async () => {
    const dir = mkdtempSync(join(tmpdir(), 'po-rules-'));
    const path = join(dir, 'rules.yaml');
    writeFileSync(path, RULES('20s'));
    const applied: Rules[] = [];
    const log = memoryLogger();
    const w = watchRules(path, new Set(['coworking', 'lounge']), (r) => applied.push(r), log, 50);
    try {
      await new Promise((r) => setTimeout(r, 100)); // FSEvents успевает подписаться
      writeFileSync(path, 'human: [сломано');
      await vi.waitFor(() => expect(log.lines.some((l) => l.level === 'error')).toBe(true), { timeout: 3000 });
      expect(applied).toEqual([]);
      writeFileSync(path, RULES('5s') + 'bus: { wait: 5s }\n');
      await vi.waitFor(() => expect(applied.at(-1)?.dwellMs.agent).toBe(5000), { timeout: 3000 });
      expect(applied.at(-1)!.busWaitMs).toBe(5000);
    } finally {
      w.close();
      rmSync(dir, { recursive: true, force: true });
    }
  });
});
