import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import { parse, stringify } from 'yaml';
import { ManualClock, OfficeHost, OfficeRuntime, VersionStore, loadOffice, memoryLogger, type RuntimeOptions } from '../src/index.ts';
import { advance, iso } from './helpers.ts';
import { officeCopy } from './admin-helpers.ts';

function setup(createRuntime?: (o: RuntimeOptions) => OfficeRuntime) {
  const { dir } = officeCopy();
  const office = loadOffice(dir);
  const clock = new ManualClock();
  const versions = new VersionStore(office.dataDir, clock);
  const log = memoryLogger();
  const host = new OfficeHost({ office, clock, log, versions, createRuntime, rulesDebounceMs: 50 });
  const resets: number[] = [];
  host.onReset = () => resets.push(1);
  return { dir, office, clock, versions, host, resets, log };
}
const swapPods = (people: string) =>
  stringify({ people: (parse(people) as { people: { id: string; pod: string }[] }).people.map((p) => (p.id === 'p1' ? { ...p, pod: 'pod:p6' } : p.id === 'p6' ? { ...p, pod: 'pod:p1' } : p)) });

describe('OfficeHost.apply (спека хостинга 4.2, 4.3)', () => {
  it('старт с admin — версия initial; apply — новая версия, файлы на диске, мир пересобран, зрители отключены', async () => {
    const { host, versions, dir, clock, resets } = setup();
    expect(versions.list().map((m) => [m.version, m.kind])).toEqual([[1, 'initial']]);
    const rt0 = host.runtime;
    rt0.ingestFromSource(rt0.sourceByName('manual')!, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }]);
    rt0.ingestFromSource(rt0.sourceByName('claude-hook')!, [{ type: 'status', agent: { project: 'P', slot: '%1' }, status: 'working', at: iso(clock) }]);
    advance(rt0, clock, 1000);
    const people = swapPods(host.current().files['people.yaml']);
    const r = await host.apply({ 'people.yaml': people }, { comment: 'поменять кабинки', baseVersion: 1 });
    expect(r.status).toBe('applied');
    expect(r.status === 'applied' && r.version).toBe(2);
    expect(readFileSync(join(dir, 'people.yaml'), 'utf8')).toBe(people);
    expect(versions.list()[0]).toMatchObject({ version: 2, kind: 'apply', comment: 'поменять кабинки' });
    expect(host.runtime).not.toBe(rt0);
    expect(host.runtime.store.get('p1')?.status).toBe('online');
    expect(host.runtime.store.get('agent:p1:P:%1')?.status).toBe('working');
    const seat = host.runtime.office.bundle.map.spotsInZone('pod:p6').find((s) => s.tags.includes('owner_seat'))!;
    const p1 = host.runtime.hello().characters.find((c) => c.id === 'p1')!;
    expect(p1.pose).toBe('sit');
    expect([Math.floor(p1.x), Math.floor(p1.y)]).toEqual([seat.x, seat.y]);
    expect(resets).toHaveLength(1);
  });

  it('ошибка проверки — ничего не меняется', async () => {
    const { host, versions, dir } = setup();
    const before = readFileSync(join(dir, 'office.yaml'), 'utf8');
    const rt0 = host.runtime;
    const r = await host.apply({ 'office.yaml': 'grid: [' });
    expect(r.status).toBe('invalid');
    expect(readFileSync(join(dir, 'office.yaml'), 'utf8')).toBe(before);
    expect(host.runtime).toBe(rt0);
    expect(versions.list()).toHaveLength(1);
  });

  it('baseVersion не совпал — conflict с текущей версией', async () => {
    const { host } = setup();
    expect(await host.apply({}, { baseVersion: 7 })).toEqual({ status: 'conflict', current: 1 });
    expect(host.check({}, { baseVersion: 7 })).toEqual({ status: 'conflict', current: 1 });
  });

  it('сбой сборки runtime — файлы и runtime прежние, версия удалена, номер не переиспользуется', async () => {
    let calls = 0;
    const { host, versions, dir } = setup((o) => {
      calls++;
      if (calls === 2) throw new Error('сборка упала');
      return new OfficeRuntime(o);
    });
    const before = readFileSync(join(dir, 'people.yaml'), 'utf8');
    const rt0 = host.runtime;
    const r = await host.apply({ 'people.yaml': swapPods(before) });
    expect(r).toEqual({ status: 'failed', message: 'версия не применена: офис не собрался на сервере, состояние офиса прежнее' });
    expect(readFileSync(join(dir, 'people.yaml'), 'utf8')).toBe(before);
    expect(host.runtime).toBe(rt0);
    expect(versions.list().map((m) => m.version)).toEqual([1]);
    const again = await host.apply({ 'people.yaml': swapPods(before) });
    expect(again.status === 'applied' && again.version).toBe(3);
  });

  it('сбой после подмены runtime (переподключение зрителей) — apply состоялся: версия, файлы, мир новые, оговорка в problems', async () => {
    const { host, versions, dir, log } = setup();
    host.onReset = () => {
      throw new Error('сокеты упали');
    };
    const rt0 = host.runtime;
    const people = swapPods(readFileSync(join(dir, 'people.yaml'), 'utf8'));
    const r = await host.apply({ 'people.yaml': people }, { baseVersion: 1 });
    expect(r.status).toBe('applied');
    expect(r.status === 'applied' && [r.version, r.problems]).toEqual([2, [expect.stringContaining('зрители не переподключены')]]);
    expect(versions.list().map((m) => m.version)).toEqual([2, 1]);
    expect(readFileSync(join(dir, 'people.yaml'), 'utf8')).toBe(people);
    expect(host.runtime).not.toBe(rt0);
    expect(log.lines.some((l) => l.level === 'error' && l.msg.includes('сокеты упали'))).toBe(true);
    expect((await host.apply({}, { baseVersion: 2 })).status).toBe('applied'); // следующий apply строится на версии 2
  });

  it('тот же набор (пустой apply, откат на текущую) — без новой версии и пересборки мира', async () => {
    const { host, versions, resets } = setup();
    const rt0 = host.runtime;
    const r = await host.apply({});
    expect(r.status === 'applied' && [r.version, r.unchanged]).toEqual([1, true]);
    const back = await host.rollback(1);
    expect(back.status === 'applied' && [back.version, back.unchanged]).toEqual([1, true]);
    expect([host.runtime, versions.list().length, resets.length]).toEqual([rt0, 1, 0]);
  });

  it('два apply подряд выполняются по очереди', async () => {
    const { host } = setup();
    const people = host.current().files['people.yaml'];
    const [a, b] = await Promise.all([host.apply({ 'people.yaml': swapPods(people) }), host.apply({ 'people.yaml': people })]);
    expect([a.status === 'applied' && a.version, b.status === 'applied' && b.version]).toEqual([2, 3]);
  });

  it('rollback — набор старой версии новой версией с kind rollback', async () => {
    const { host, versions, dir } = setup();
    const v1 = host.current().files;
    await host.apply({ 'people.yaml': swapPods(v1['people.yaml']) });
    const r = await host.rollback(1, 'назад');
    expect(r.status === 'applied' && r.version).toBe(3);
    expect(versions.list()[0]).toMatchObject({ version: 3, kind: 'rollback', comment: 'назад' });
    expect(readFileSync(join(dir, 'people.yaml'), 'utf8')).toBe(v1['people.yaml']);
    expect(await host.rollback(99)).toEqual({ status: 'not_found' });
  });

  it('после apply с переименованной зоной ручная правка rules.yaml с новой зоной применяется', async () => {
    const { host, dir } = setup();
    host.watch();
    try {
      const cur = host.current().files;
      const office = cur['office.yaml'].replaceAll('lounge', 'chill');
      const rules = cur['rules.yaml'].replaceAll('lounge', 'chill');
      const r = await host.apply({ 'office.yaml': office, 'rules.yaml': rules });
      expect(r.status).toBe('applied');
      const spy = vi.spyOn(host.runtime, 'setRules');
      await new Promise((res) => setTimeout(res, 150)); // FSEvents успевает подписаться
      writeFileSync(join(dir, 'rules.yaml'), rules.replace('dwell: { agent: 2s', 'dwell: { agent: 3s'));
      await vi.waitFor(() => expect(spy).toHaveBeenCalled(), { timeout: 3000 });
    } finally {
      host.close();
    }
  });
});

describe('ручная правка на работающем сервере — версия manual до apply (спека хостинга 6 п. 3)', () => {
  it('частичный apply берёт правленый руками rules.yaml, а не файл из истории; старый baseVersion — 409', async () => {
    const { host, versions, dir } = setup();
    const rules = readFileSync(join(dir, 'rules.yaml'), 'utf8').replace('dwell: { agent: 2s', 'dwell: { agent: 3s');
    writeFileSync(join(dir, 'rules.yaml'), rules);
    const people = swapPods(readFileSync(join(dir, 'people.yaml'), 'utf8'));
    expect(await host.apply({ 'people.yaml': people }, { baseVersion: 1 })).toEqual({ status: 'conflict', current: 2 });
    expect(versions.list().map((m) => [m.version, m.kind])).toEqual([[2, 'manual'], [1, 'initial']]);
    const r = await host.apply({ 'people.yaml': people }, { baseVersion: 2 });
    expect(r.status === 'applied' && r.version).toBe(3);
    expect(readFileSync(join(dir, 'rules.yaml'), 'utf8')).toBe(rules);
    expect(versions.read(3)!.files['rules.yaml']).toBe(rules);
  });

  it('GET office (host.office) — ручная правка видна сразу, версией manual', async () => {
    const { host, dir } = setup();
    writeFileSync(join(dir, 'people.yaml'), swapPods(readFileSync(join(dir, 'people.yaml'), 'utf8')));
    const cur = await host.office();
    expect(cur.version).toBe(2);
    expect(cur.files['people.yaml']).toBe(readFileSync(join(dir, 'people.yaml'), 'utf8'));
    expect((await host.office()).version).toBe(2); // без правки — та же версия
  });
});

describe('ручная правка между запусками — версия manual (спека хостинга 6 п. 3)', () => {
  it('файлы отличаются от последней версии — manual при создании OfficeHost', () => {
    const { dir, office, versions } = setup();
    writeFileSync(join(dir, 'rules.yaml'), readFileSync(join(dir, 'rules.yaml'), 'utf8') + '# руками\n');
    new OfficeHost({ office: loadOffice(dir), clock: new ManualClock(), log: memoryLogger(), versions: new VersionStore(office.dataDir, new ManualClock()) });
    expect(versions.list().map((m) => m.kind)).toEqual(['manual', 'initial']);
  });
});
