import { cpSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { ManualClock, OfficeHost, VersionStore, loadOffice, memoryLogger } from '../src/index.ts';

const TEMPLATE = fileURLToPath(new URL('../../../offices/hosted-template/', import.meta.url));
const CATALOG = fileURLToPath(new URL('../../../catalog/limezu/catalog.yaml', import.meta.url));

// Как развёртывание из памятки: копия шаблона, init (случайные токены), абсолютный catalog, свои пути хоста.
function deploy(): string {
  const root = mkdtempSync(join(tmpdir(), 'po-hosted-'));
  const dir = join(root, 'office');
  cpSync(TEMPLATE, dir, { recursive: true });
  let n = 0;
  const text = readFileSync(join(dir, 'config.example.yaml'), 'utf8')
    .replace(/CHANGE_ME_[A-Za-z0-9_]+/g, () => `token-${++n}-abcdefgh-abcdefgh-abcd`)
    .replace(/^catalog: .*$/m, `catalog: ${CATALOG}`)
    .replaceAll('/var/lib/pixeloffice/<офис>', root);
  writeFileSync(join(dir, 'config.yaml'), text);
  return dir;
}

describe('шаблон офиса коллеги (спека хостинга 11.1)', () => {
  it('стартует: admin, один зритель, источник с owner и humans, без лишних источников и relay', () => {
    const office = loadOffice(deploy());
    const c = office.bundle.config;
    expect(c.admin?.token).toMatch(/^token-/);
    expect(c.viewerTokens).toHaveLength(1);
    expect(c.sources).toHaveLength(1);
    expect(c.sources[0]).toMatchObject({ owner: 'colleague', humans: true, ttlSec: { online: 43200, meeting: 43200, working: 900 } });
    expect(c.relay).toBeUndefined();
    expect(c.people.map((p) => p.id)).toEqual(['colleague']);
    expect(office.bundle.warnings).toEqual([]);
  });
  it('API готов: первая версия initial', () => {
    const office = loadOffice(deploy());
    const versions = new VersionStore(office.dataDir, new ManualClock());
    new OfficeHost({ office, clock: new ManualClock(), log: memoryLogger(), versions });
    expect(versions.list().map((m) => m.kind)).toEqual(['initial']);
  });
});

describe('шаблон: токены через admin API (спека admin-tokens 6.2, 6.3)', () => {
  const read = (f: string) => readFileSync(join(TEMPLATE, f), 'utf8');
  it('for-ai.md: отдельный токен второму человеку — POST-ом, передавать лично', () => {
    const md = read('for-ai.md');
    expect(md).toContain('tokens/sources');
    expect(md).toContain('лично');
  });
  it('README.md: выдача через API и tokens.json в бэкапе', () => {
    const md = read('README.md');
    expect(md).toContain('/v1/admin/tokens/');
    expect(md).toContain('tokens.json');
  });
});
