import { describe, expect, it } from 'vitest';
import { EventsBodySchema, formatIssues, isAgentStatus, isHumanStatus } from '../src/index.ts';

const at = '2026-10-20T10:00:00.000Z';
const issuesOf = (body: unknown) => {
  const r = EventsBodySchema.safeParse(body);
  return r.success ? [] : formatIssues(r.error);
};

describe('EventsBodySchema', () => {
  it('project «.» и «..» → ошибка с путём поля: в адресе облика проекта браузер схлопывает такой сегмент (спека агентов §3.4)', () => {
    const agent = (project: string) => ({ events: [{ type: 'status', agent: { project, slot: '%1' }, status: 'working', at }] });
    for (const p of ['.', '..']) expect(issuesOf(agent(p)).map((i) => i.path)).toContain('events.0.agent.project');
    for (const p of ['...', '.x', 'a..b']) expect(issuesOf(agent(p))).toEqual([]);
  });

  it('статус человека по entityId', () => {
    expect(EventsBodySchema.safeParse({ events: [{ type: 'status', entityId: 'stas', status: 'online', at }] }).success).toBe(true);
  });

  it('idle и needs_input — статусы и людей, и агентов (спека 17.11.2026)', () => {
    for (const s of ['idle', 'needs_input'] as const) {
      expect(EventsBodySchema.safeParse({ events: [{ type: 'status', entityId: 'stas', status: s, at }] }).success).toBe(true);
      expect(isHumanStatus(s)).toBe(true);
      expect(isAgentStatus(s)).toBe(true);
    }
  });

  it('статус агента через agent', () => {
    const body = { events: [{ type: 'status', agent: { project: 'PixelOffice', projectDir: '/p/PixelOffice', slot: '%17' }, status: 'working', at, ttlSec: 900 }] };
    expect(EventsBodySchema.safeParse(body).success).toBe(true);
  });

  it('entityId вида agent:… → ошибка с путём поля', () => {
    const issues = issuesOf({ events: [{ type: 'status', entityId: 'agent:stas:x:%1', status: 'working', at }] });
    expect(issues.map((i) => i.path)).toContain('events.0.entityId');
  });

  it('управляющие символы в идентификаторах и «:» в slot → ошибка с путём поля', () => {
    const agent = (project: string, slot: string) => ({ events: [{ type: 'status', agent: { project, slot }, status: 'working', at }] });
    expect(issuesOf(agent('a\n\nb', '%1')).map((i) => i.path)).toContain('events.0.agent.project');
    expect(issuesOf(agent('b', 'x:%1')).map((i) => i.path)).toContain('events.0.agent.slot');
    expect(issuesOf({ events: [{ type: 'status', entityId: 'p1\r', status: 'online', at }] }).map((i) => i.path)).toContain('events.0.entityId');
    expect(issuesOf(agent('b:x', 'abc-123'))).toEqual([]); // «:» в project допустим: slot без «:» делает ключ однозначным
  });

  it('нужно ровно одно из entityId и agent', () => {
    expect(issuesOf({ events: [{ type: 'status', status: 'online', at }] }).map((i) => i.path)).toContain('events.0.entityId');
    const both = { type: 'bubble', entityId: 'stas', agent: { project: 'p', slot: 's' }, text: 'hi', ttlSec: 10, at };
    expect(issuesOf({ events: [both] }).map((i) => i.path)).toContain('events.0.entityId');
  });

  it('source и owner в теле запрещены', () => {
    expect(issuesOf({ events: [{ type: 'status', entityId: 'stas', status: 'online', at, source: 'x' }] }).length).toBeGreaterThan(0);
  });

  it('невалидное время → путь events.0.at', () => {
    expect(issuesOf({ events: [{ type: 'status', entityId: 'stas', status: 'online', at: 'вчера' }] }).map((i) => i.path)).toContain('events.0.at');
  });

  it('snapshot со списком сущностей', () => {
    const body = { events: [{ type: 'snapshot', at, ttlSec: 120, entities: [{ entityId: 'stas', status: 'meeting', meetingId: 'room1' }] }] };
    expect(EventsBodySchema.safeParse(body).success).toBe(true);
  });

  it('пустой список событий → ошибка', () => {
    expect(issuesOf({ events: [] }).map((i) => i.path)).toContain('events');
  });
});

describe('метка агента (спека метки §4.1)', () => {
  const st = (extra: object) => ({ events: [{ type: 'status', agent: { project: 'p', slot: '%1' }, status: 'working', at, ...extra }] });

  it('метка с текстом и null принимаются; поля может не быть', () => {
    expect(issuesOf(st({ label: { text: 'tmux names', private: false } }))).toEqual([]);
    expect(issuesOf(st({ label: { text: 'x'.repeat(100), private: true } }))).toEqual([]);
    expect(issuesOf(st({ label: null }))).toEqual([]);
    expect(issuesOf(st({}))).toEqual([]);
  });

  it('управляющие символы, пустой текст, одни пробелы, длина 101 → ошибка с путём events.0.label.text', () => {
    for (const text of ['a\nb', '\u0007', '', '   ', 'x'.repeat(101)]) {
      expect(issuesOf(st({ label: { text, private: false } })).map((i) => i.path)).toContain('events.0.label.text');
    }
  });

  it('длина считается в единицах UTF-16, не в кодовых точках: 50 эмодзи (100 единиц) проходят, 101 и больше — нет (спека метки §4.1.1)', () => {
    expect(issuesOf(st({ label: { text: '😀'.repeat(50), private: false } }))).toEqual([]);
    for (const text of ['😀'.repeat(50) + 'x', '😀'.repeat(51)]) {
      expect(issuesOf(st({ label: { text, private: false } })).map((i) => i.path)).toContain('events.0.label.text');
    }
  });

  it('без private и с лишним полем — ошибка', () => {
    expect(issuesOf(st({ label: { text: 'x' } })).map((i) => i.path)).toContain('events.0.label.private');
    expect(issuesOf(st({ label: { text: 'x', private: false, pane: '%1' } })).length).toBeGreaterThan(0);
  });

  it('label у события с entityId → ошибка с путём events.0.label; у облачка поля нет', () => {
    expect(issuesOf({ events: [{ type: 'status', entityId: 'p1', status: 'online', at, label: null }] }).map((i) => i.path)).toContain('events.0.label');
    const bubble = { type: 'bubble', agent: { project: 'p', slot: '%1' }, text: 'hi', ttlSec: 10, at };
    expect(issuesOf({ events: [bubble] })).toEqual([]);
    // строгий объект: неизвестный ключ label отвергается на самом событии
    expect(issuesOf({ events: [{ ...bubble, label: null }] }).map((i) => i.path)).toEqual(['events.0']);
  });
});

describe('адресат события bubble (спека адресных сообщений 2.1)', () => {
  const at = '2026-11-20T09:00:00.000Z';
  it('to: "all" и список id людей принимаются; пустой список — адресата нет', () => {
    expect(issuesOf({ events: [{ type: 'bubble', entityId: 'stas', text: 'привет', ttlSec: 10, to: 'all', at }] })).toEqual([]);
    expect(issuesOf({ events: [{ type: 'bubble', entityId: 'stas', text: 'привет', ttlSec: 10, to: ['p1', 'p2'], at }] })).toEqual([]);
    expect(issuesOf({ events: [{ type: 'bubble', entityId: 'stas', text: 'привет', ttlSec: 10, to: [], at }] })).toEqual([]);
  });

  it('агентское событие с to → ошибка с путём events.0.to: сообщение агента всегда адресовано хозяину (2.1.3)', () => {
    const ev = { type: 'bubble', agent: { project: 'p', slot: '%1' }, text: 'hi', ttlSec: 10, to: ['p1'], at };
    expect(issuesOf({ events: [ev] }).map((i) => i.path)).toEqual(['events.0.to']);
    expect(issuesOf({ events: [{ ...ev, to: 'all' }] }).map((i) => i.path)).toEqual(['events.0.to']);
  });

  it('id агента в to → ошибка: адресаты — только люди', () => {
    const ev = { type: 'bubble', entityId: 'stas', text: 'hi', ttlSec: 10, to: ['agent:p1:p:%1'], at };
    expect(issuesOf({ events: [ev] }).map((i) => i.path)).toEqual(['events.0.to.0']);
  });
});

describe('at необязателен (спека хостинга 9)', () => {
  it('status, snapshot и bubble без at проходят схему', () => {
    const body = {
      events: [
        { type: 'status', entityId: 'p1', status: 'online' },
        { type: 'snapshot', entities: [{ entityId: 'p1', status: 'online' }] },
        { type: 'bubble', entityId: 'p1', text: 'привет', ttlSec: 30 },
      ],
    };
    expect(EventsBodySchema.safeParse(body).success).toBe(true);
  });
  it('неверный at по-прежнему отвергается', () => {
    expect(EventsBodySchema.safeParse({ events: [{ type: 'status', entityId: 'p1', status: 'online', at: 'вчера' }] }).success).toBe(false);
  });
});
