import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { ManualClock, OfficeRuntime, Persistence, memoryLogger, statusRows, statusTable } from '../src/index.ts';
import { demoOffice, iso } from './helpers.ts';

const T0 = Date.UTC(2026, 9, 23, 9, 0);
const hook = (slot: string) => ({ project: 'PixelOffice', projectDir: '/x/PixelOffice', slot });

// Состояние, как его видит статус: снимок + хвост журнала из dataDir (так же сервер восстанавливается при старте).
function restored() {
  const dir = mkdtempSync(join(tmpdir(), 'po-status-'));
  const clock = new ManualClock(T0);
  const p = new Persistence(dir, 30, memoryLogger());
  const a = new OfficeRuntime({ office: demoOffice(), clock, log: memoryLogger(), eventLog: p.log });
  const nc = a.sourceByName('manual')!;
  const cc = a.sourceByName('claude-hook')!;
  a.ingestFromSource(nc, [{ type: 'status', entityId: 'p1', status: 'online', ttlSec: 3600, at: iso(clock) }]);
  a.ingestFromSource(cc, [
    { type: 'status', agent: hook('%1'), status: 'working', at: iso(clock) },
    { type: 'status', agent: hook('%2'), status: 'idle', at: iso(clock) },
  ]);
  a.ingestFromSource(cc, [
    { type: 'status', agent: hook('%2'), status: 'offline', at: iso(clock) },
  ]);
  p.saveState(a.persistedState());
  clock.advance(5 * 60_000);
  // После снимка — только в журнале.
  a.ingestFromSource(nc, [{ type: 'status', entityId: 'p2', status: 'meeting', meetingId: 'm1', ttlSec: 3600, at: iso(clock) }]);
  a.ingestFromSource(cc, [
    { type: 'status', agent: hook('%1'), status: 'needs_input', at: iso(clock) },
    { type: 'bubble', agent: hook('%1'), text: 'Разрешить pnpm test?', ttlSec: 60, at: iso(clock) },
  ]);
  clock.advance(2 * 60_000);
  const b = new OfficeRuntime({ office: demoOffice(), clock, log: memoryLogger() });
  b.restore(new Persistence(dir, 30, memoryLogger()));
  return { rt: b, now: clock.now() };
}

describe('statusRows (спека хостинга 5.6)', () => {
  it('те же данные, что у status --all: люди и все агенты, время ISO, срок по TTL', () => {
    const { rt, now } = restored();
    const rows = statusRows(rt, now);
    const p1 = rows.find((r) => r.id === 'p1')!;
    expect(p1).toMatchObject({ kind: 'human', name: 'Стас', label: 'Стас', status: 'online', source: 'manual' });
    expect(Date.parse(p1.at!)).toBe(now - 7 * 60_000);
    expect(p1.expiresAt).toBe(new Date(Date.parse(p1.at!) + 3600_000).toISOString());
    expect(rows.find((r) => r.id === 'p3')).toMatchObject({ status: 'offline', source: null, at: null });
    expect(rows.find((r) => r.id === 'p2')).toMatchObject({ status: 'meeting', meetingId: 'm1' });
    expect(rows.find((r) => r.id === 'agent:p1:PixelOffice:%1')).toMatchObject({ kind: 'agent', status: 'needs_input', question: 'Разрешить pnpm test?' });
    expect(rows.some((r) => r.id === 'agent:p1:PixelOffice:%2')).toBe(true); // offline-агент тоже
  });
});

describe('statusTable', () => {
  it('люди все, агенты без offline; статус, давность, источник, вопрос ждущего', () => {
    const { rt, now } = restored();
    const lines = statusTable(rt, { now }).split('\n');
    expect(lines[0]).toMatch(/^ID\s+ПОДПИСЬ\s+СТАТУС\s+ДАВНО\s+ИСТОЧНИК$/);
    const row = (id: string) => lines.find((l) => l.startsWith(`${id} `))?.split(/\s{2,}/);
    expect(row('p1')).toEqual(['p1', 'Стас', 'online', '7 мин', 'manual']);
    expect(row('p2')).toEqual(['p2', 'Борис', 'meeting m1', '2 мин', 'manual']);
    expect(row('p3')).toEqual(['p3', 'Вера', 'offline', '—', '—']);
    expect(row('agent:p1:PixelOffice:%1')).toEqual(['agent:p1:PixelOffice:%1', 'Стас · PixelOffice', 'needs_input', '2 мин', 'claude-hook', '«Разрешить pnpm test?»']);
    expect(row('agent:p1:PixelOffice:%2')).toBeUndefined();
    expect(lines.at(-1)).toBe('агентов offline скрыто: 1 (--all — показать)');
  });

  it('--all: offline-агенты тоже, без строки о скрытых', () => {
    const { rt, now } = restored();
    const out = statusTable(rt, { now, all: true });
    expect(out).toMatch(/^agent:p1:PixelOffice:%2\s+Стас · PixelOffice 2\s+offline\s+7 мин\s+claude-hook$/m);
    expect(out).not.toContain('скрыто');
  });
});
