import { readFileSync } from 'node:fs';
import { parseConfigWithPeople, type SourceConfig } from '@pixeloffice/core';
import type { Event } from '@pixeloffice/protocol';
import { readOfficeTexts } from '@pixeloffice/validate-maps';
import { playTimed } from './play.ts';
import { resolveScenarioSource, scenarios } from './scenarios.ts';

// Реплей в /v1/events. Время события (at) — момент отправки (решение 22).
const USAGE = `использование:
  node tools/replay/src/cli.ts scenario <имя> --office <каталог> --url <http://host:port> [--speed 1] [--seed 1]
  node tools/replay/src/cli.ts log <events.jsonl> --office <каталог> --url <http://host:port> [--speed 10]
сценарии: ${Object.keys(scenarios).join(', ')}`;

class CliError extends Error {
  code: number;
  constructor(message: string, code = 1) {
    super(message);
    this.code = code;
  }
}

async function main(): Promise<void> {
  const [mode, arg, ...rest] = process.argv.slice(2);
  const opt = (name: string, def?: string) => (rest.includes(`--${name}`) ? rest[rest.indexOf(`--${name}`) + 1] : def);
  const officeDir = opt('office');
  const url = opt('url');
  if (!mode || !arg || !officeDir || !url) throw new CliError(USAGE, 2);
  if (mode !== 'scenario' && mode !== 'log') throw new CliError(USAGE, 2);
  const base = URL.canParse(url) ? new URL(url) : null;
  if (!base) throw new CliError(`некорректный --url «${url}»`, 2);

  const cfg = parseConfigWithPeople(readOfficeTexts(officeDir).texts); // люди — из people.yaml (спека хостинга 3.1)
  if (!cfg.ok) throw new CliError(cfg.errors.map((e) => e.message).join('\n'));
  const config = cfg.value.config;
  const speed = Number(opt('speed', mode === 'log' ? '10' : '1'));
  if (!(speed > 0)) throw new CliError('--speed должен быть положительным числом', 2);

  async function post(source: SourceConfig, events: Event[]): Promise<void> {
    const now = new Date().toISOString();
    let res: Response;
    try {
      res = await fetch(new URL('/v1/events', base!), {
        method: 'POST',
        headers: { 'content-type': 'application/json', authorization: `Bearer ${source.token}` },
        body: JSON.stringify({ events: events.map((e) => ({ ...e, at: now })) }),
      });
    } catch (e) {
      throw new CliError(`сервер ${base!.origin} недоступен: ${e instanceof Error ? (e.cause instanceof Error ? e.cause.message : e.message) : String(e)}`);
    }
    const text = await res.text();
    console.log(`${new Date().toLocaleTimeString()} ${source.source} ×${events.length} → ${res.status} ${text}`);
  }

  if (mode === 'scenario') {
    const s = scenarios[arg];
    if (!s) throw new CliError(`нет сценария «${arg}»\n${USAGE}`, 2);
    const agentSrc = resolveScenarioSource(config.sources, 'agent');
    const humanSrc = resolveScenarioSource(config.sources, 'human');
    const people = config.people.map((p) => p.id);
    const evs = s.build({ people, owner: agentSrc?.owner ?? people[0] ?? '', seed: Number(opt('seed', '1')), baseTime: Date.now() });
    await playTimed(
      evs.map((e) => ({ atMs: e.atMs, item: e })),
      async (batch) => {
        for (const kind of ['human', 'agent'] as const) {
          const src = kind === 'agent' ? agentSrc : humanSrc;
          const part = batch.filter((e) => e.source === kind).map((e) => e.event);
          if (part.length && src) await post(src, part);
          else if (part.length) console.warn(`нет источника для событий «${kind}» в конфиге — пропущено ${part.length}`);
        }
      },
      speed,
    );
  } else {
    const entries = readFileSync(arg, 'utf8')
      .split('\n')
      .filter((l) => l.trim())
      .map((l, i) => {
        try {
          return JSON.parse(l) as { receivedAt: number; source: string; event: Event };
        } catch {
          throw new CliError(`${arg}: строка ${i + 1} — не JSON`);
        }
      });
    const t0 = entries[0]?.receivedAt ?? 0;
    const byName = new Map(config.sources.map((s) => [s.source, s]));
    await playTimed(
      entries.map((e) => ({ atMs: e.receivedAt - t0, item: e })),
      async (batch) => {
        for (const name of new Set(batch.map((e) => e.source))) {
          const src = byName.get(name);
          if (!src) {
            console.warn(`источника «${name}» нет в конфиге — пропуск`);
            continue;
          }
          await post(src, batch.filter((e) => e.source === name).map((e) => e.event));
        }
      },
      speed,
    );
  }
}

main().catch((e: unknown) => {
  if (e instanceof CliError) console.error(e.message);
  else console.error(`ошибка: ${e instanceof Error ? e.message : String(e)}`);
  process.exit(e instanceof CliError ? e.code : 1);
});
