import { mulberry32 } from '@pixeloffice/core';
import type { Event, Status } from '@pixeloffice/protocol';

// Логический источник: реальный (с токеном) подставляет resolveScenarioSource.
export type ScenarioEvent = { atMs: number; source: 'human' | 'agent'; event: Event };
export type ScenarioContext = { people: string[]; owner: string; seed: number; baseTime: number };
export type Scenario = { name: string; description: string; build(ctx: ScenarioContext): ScenarioEvent[] };

// Проекты агентов сценариев. Облик агента — облик его проекта, одновременные агенты проекта различаются номером
// и цветом одежды: 20 агентов в одном проекте были бы толпой клонов с номерами до 20.
export const PROJECTS = ['demo', 'api', 'site', 'infra', 'docs'] as const;
const at = (ctx: ScenarioContext, ms: number) => new Date(ctx.baseTime + ms).toISOString();
const human = (ctx: ScenarioContext, atMs: number, entityId: string, status: Status): ScenarioEvent => ({
  atMs,
  source: 'human',
  event: { type: 'status', entityId, status, at: at(ctx, atMs) },
});
const agent = (ctx: ScenarioContext, atMs: number, slot: string, status: Status, project: string = PROJECTS[0]): ScenarioEvent => ({
  atMs,
  source: 'agent',
  event: { type: 'status', agent: { project, slot }, status, at: at(ctx, atMs) },
});
const bubble = (ctx: ScenarioContext, atMs: number, slot: string, text: string, ttlSec: number, project: string = PROJECTS[0]): ScenarioEvent => ({
  atMs,
  source: 'agent',
  event: { type: 'bubble', agent: { project, slot }, text, ttlSec, at: at(ctx, atMs) },
});
const humanBubble = (ctx: ScenarioContext, atMs: number, entityId: string, text: string, ttlSec: number, to?: 'all' | string[]): ScenarioEvent => ({
  atMs,
  source: 'human',
  event: { type: 'bubble', entityId, text, ttlSec, at: at(ctx, atMs), ...(to !== undefined ? { to } : {}) },
});
const sorted = (xs: ScenarioEvent[]) => xs.sort((a, b) => a.atMs - b.atMs);
// Вопросы сценария queue-full — по одному на агента, в порядке слотов.
const QUESTIONS = ['Разрешить запуск pnpm test?', 'Можно обновить зависимости?', 'Деплой на creative поднять?', 'Создать ветку для правки?', 'Запушить коммит в мастер?', 'Перезапустить сервер офиса?', 'Удалить старую ветку?'];

export const scenarios: Record<string, Scenario> = {
  morning: {
    name: 'morning',
    description: 'утро — все приходят по одному, у хозяина просыпаются два агента одного проекта',
    build: (ctx) =>
      sorted([...ctx.people.map((p, i) => human(ctx, 1500 * i, p, 'online')), agent(ctx, 3000, '%1', 'working'), agent(ctx, 4000, '%2', 'working')]),
  },
  meeting9: {
    name: 'meeting9',
    description: 'встреча на 9 человек в самой подходящей переговорке',
    build: (ctx) => {
      if (ctx.people.length < 9) throw new Error(`meeting9: нужно минимум 9 людей, в офисе ${ctx.people.length}`);
      const online = ctx.people.map((p, i) => human(ctx, 500 * i, p, 'online'));
      const snapshot: ScenarioEvent = {
        atMs: 20_000,
        source: 'human',
        event: {
          type: 'snapshot',
          at: at(ctx, 20_000),
          entities: ctx.people.map((p, i) => (i < 9 ? { entityId: p, status: 'meeting' as const, meetingId: 'standup' } : { entityId: p, status: 'online' as const })),
        },
      };
      return sorted([...online, snapshot]);
    },
  },
  agents20: {
    name: 'agents20',
    description: '20 агентов в 5 проектах дёргаются working↔idle',
    build: (ctx) => {
      const rnd = mulberry32(ctx.seed);
      const out: ScenarioEvent[] = [human(ctx, 0, ctx.people[0] ?? ctx.owner, 'online')];
      for (let i = 1; i <= 20; i++) {
        let t = Math.floor(rnd() * 3000);
        let working = true;
        while (t < 120_000) {
          out.push(agent(ctx, t, `%${i}`, working ? 'working' : 'idle', PROJECTS[(i - 1) % PROJECTS.length]));
          working = !working;
          t += 3000 + Math.floor(rnd() * 12_000);
        }
      }
      return sorted(out);
    },
  },
  'needs-input': {
    name: 'needs-input',
    description: 'агент ждёт разрешения, второй болтает, третье сообщение снялось, человек спрашивает — окно и очередь (спека диалоговых окон 4.5)',
    build: (ctx) =>
      sorted([
        human(ctx, 0, ctx.owner, 'online'),
        // Человек — со статусом: без него человек невидим для мира (visible: false при создании, setBubble видимость
        // не поднимает), и его bubble не доедет ни в hello, ни в delta.
        ...(ctx.people[1] ? [human(ctx, 0, ctx.people[1], 'online'), humanBubble(ctx, 11_000, ctx.people[1], 'Кофе в кухне кончился', 3600, [ctx.owner])] : []),
        agent(ctx, 0, '%1', 'working'),
        agent(ctx, 10_000, '%1', 'needs_input'),
        bubble(ctx, 10_000, '%1', 'Разрешить запуск pnpm test?', 3600),
        agent(ctx, 0, '%2', 'working', 'api'),
        bubble(ctx, 12_000, '%2', 'Deploy на creative поднят, проверьте сайт', 3600, 'api'),
        agent(ctx, 0, '%3', 'working', 'site'),
        bubble(ctx, 5000, '%3', 'Собираю страницу документации', 3, 'site'), // ttl 3 с: к 8 с облако снято — приглушённый элемент живого прогона
      ]),
  },
  // Адресные сообщения (спека адресных сообщений 2.5.2): личное человеку, объявление всем и агентское хозяину —
  // на этот сценарий смотрит тест-режим me=p1 / me=p2 и скриншоты.
  addressed: {
    name: 'addressed',
    description: 'адресные сообщения: личное человеку, объявление всем, агент — хозяину (фильтрация me=…)',
    build: (ctx) =>
      sorted([
        human(ctx, 0, ctx.owner, 'online'),
        ...(ctx.people[1] ? [human(ctx, 0, ctx.people[1], 'online'), humanBubble(ctx, 8000, ctx.people[1], 'Задеплоила статику, посмотри сайт', 3600, [ctx.owner])] : []),
        ...(ctx.people[2] ? [human(ctx, 0, ctx.people[2], 'online'), humanBubble(ctx, 9000, ctx.people[2], 'Обед в час на кухне — все', 3600, 'all')] : []),
        agent(ctx, 0, '%1', 'working'),
        bubble(ctx, 10_000, '%1', 'Тесты зелёные, можно деплоить', 3600),
      ]),
  },
  // Предел очереди (спека предела очереди 4.4): семь агентов с живыми вопросами — на кадре пять карточек и счётчик
  // «ещё 2» (спека счётчика). Все bubble приходят одним hello, время прихода одно: порядок очереди — порядок hello (по слотам).
  'queue-full': {
    name: 'queue-full',
    description: 'семь агентов ждут ответа — очередь за пределом: пять карточек и счётчик (спека предела очереди 4.4)',
    build: (ctx) =>
      sorted([
        human(ctx, 0, ctx.owner, 'online'),
        ...[1, 2, 3, 4, 5, 6, 7].map((i) => agent(ctx, 0, `%${i}`, 'needs_input', PROJECTS[(i - 1) % PROJECTS.length])),
        ...[1, 2, 3, 4, 5, 6, 7].map((i) => bubble(ctx, 0, `%${i}`, QUESTIONS[i - 1]!, 3600, PROJECTS[(i - 1) % PROJECTS.length])),
      ]),
  },
  lounge: {
    name: 'lounge',
    description: 'агенты пяти проектов закончили и отдыхают в лаунже',
    build: (ctx) => sorted([human(ctx, 0, ctx.owner, 'online'), ...[1, 2, 3, 4, 5].map((i) => agent(ctx, (i - 1) * 500, `%${i}`, 'idle', PROJECTS[i - 1]))]),
  },
  sit4: {
    name: 'sit4',
    description: 'четыре направления сидения',
    // Двое на своих местах в кабинках (лицом на юг и на север), двое на встрече вдвоём — в малой переговорке,
    // где первые по порядку места — боковые кресла (лицом на восток и на запад).
    build: (ctx) => {
      const [a, b, c, d] = ctx.people;
      const meet = (who: string): ScenarioEvent => ({
        atMs: 0,
        source: 'human',
        event: { type: 'status', entityId: who, status: 'meeting', meetingId: 'sit4', at: at(ctx, 0) },
      });
      return sorted([...[a, b].flatMap((p) => (p ? [human(ctx, 0, p, 'online')] : [])), ...[c, d].flatMap((p) => (p ? [meet(p)] : []))]);
    },
  },
  // Сервер восстанавливает статусы при перезапуске: чтобы снова увидеть приход, сначала все уходят (tools/morning.sh).
  leave: {
    name: 'leave',
    description: 'все уходят по одному, агенты утра (%1, %2) — в капсулы',
    build: (ctx) =>
      sorted([...ctx.people.map((p, i) => human(ctx, 300 * i, p, 'offline')), agent(ctx, 0, '%1', 'offline'), agent(ctx, 500, '%2', 'offline')]),
  },
  evening: {
    name: 'evening',
    description: 'вечер: все уходят разными способами (машина, автобус, парк, метро), агенты — в капсулы; утром возвращаются',
    // Способы людей — в offices/demo/config.yaml (спека маршрутов 6.6): p1, p2, p8, p9 — машина, p3, p4 — автобус, p5 — парк.
    build: (ctx) =>
      sorted([
        ...ctx.people.map((p, i) => human(ctx, 300 * i, p, 'online')),
        agent(ctx, 3000, '%1', 'working'),
        agent(ctx, 4000, '%2', 'working'),
        ...ctx.people.map((p, i) => human(ctx, 45_000 + 700 * i, p, 'offline')),
        agent(ctx, 45_000, '%1', 'offline'),
        agent(ctx, 45_500, '%2', 'offline'),
        ...ctx.people.map((p, i) => human(ctx, 120_000 + 1000 * i, p, 'online')),
      ]),
  },
};

// Источник сценария: агентам — с owner; людям — без owner, а нет такого — с humans: true (офис коллеги, спека хостинга 10).
export function resolveScenarioSource<S extends { owner?: string; humans?: boolean }>(sources: S[], kind: 'human' | 'agent'): S | undefined {
  if (kind === 'agent') return sources.find((s) => s.owner !== undefined);
  return sources.find((s) => s.owner === undefined) ?? sources.find((s) => s.humans === true);
}
