import { describe, expect, it } from 'vitest';
import {
  ActionSchema,
  AdminConfigResponseSchema,
  AdminMatchRequestSchema,
  AdminMatchResponseSchema,
  DirSchema,
  JoinRequestSchema,
  JoinResponseSchema,
  MatchScoreSchema,
  RoundResultSchema,
  StateResponseSchema,
  TeamSchema,
} from '../src/protocol.ts';

// Направления арены — 8 значений (спека диагоналей 3.1): кардиналы как были, плюс четыре диагонали.
describe('DirSchema (спека диагоналей 3.1)', () => {
  it('перечисляет все 8 направлений', () => {
    expect(DirSchema.options).toEqual([
      'up', 'right', 'down', 'left', 'up-left', 'up-right', 'down-left', 'down-right',
    ]);
  });

  it('move и turn принимают диагонали', () => {
    expect(ActionSchema.parse({ type: 'move', dir: 'up-left' })).toEqual({ type: 'move', dir: 'up-left' });
    expect(ActionSchema.parse({ type: 'turn', facing: 'down-right' })).toEqual({ type: 'turn', facing: 'down-right' });
  });

  it('чужое слово — невалидно', () => {
    expect(DirSchema.safeParse('north').success).toBe(false);
    expect(DirSchema.safeParse('upleft').success).toBe(false);
    expect(ActionSchema.safeParse({ type: 'move', dir: 'ur' }).success).toBe(false);
  });
});

// Команды team-режима (спека командного боя 3.1, 5): все поля optional — в FFA их нет вовсе.
const mapInfo = { origin: [0, 0], size: [1, 1], cells: [['.']], walkable: [[1]], building: [0, 0, 1, 1], legend: {} };
const stateBody = { t: 0, round: 1, agents: [], projectiles: [], score: [], tournament: [], feed: [] };

describe('TeamSchema и командные поля (спека командного боя 5)', () => {
  it('перечисляет red и blue, чужое слово невалидно', () => {
    expect(TeamSchema.options).toEqual(['red', 'blue']);
    expect(TeamSchema.safeParse('green').success).toBe(false);
  });

  it('join-запрос: optional team, без него тоже валиден', () => {
    expect(JoinRequestSchema.parse({ name: 'Аня', team: 'red' })).toEqual({ name: 'Аня', team: 'red' });
    expect(JoinRequestSchema.parse({ name: 'Аня' })).toEqual({ name: 'Аня' });
    expect(JoinRequestSchema.safeParse({ name: 'Аня', team: 'green' }).success).toBe(false);
  });

  it('join-ответ с team и без team валиден', () => {
    expect(JoinResponseSchema.safeParse({ agentId: 'a1', letter: 'A', team: 'red', map: mapInfo, score: [], feed: [] }).success).toBe(true);
    expect(JoinResponseSchema.safeParse({ agentId: 'a1', letter: 'A', map: mapInfo, score: [], feed: [] }).success).toBe(true);
  });

  it('state: teams сверху, team у агентов и у self — optional', () => {
    expect(StateResponseSchema.safeParse({ ...stateBody, teams: [{ team: 'red', kills: 1 }, { team: 'blue', kills: 0 }] }).success).toBe(true);
    expect(StateResponseSchema.safeParse(stateBody).success).toBe(true);
    expect(
      StateResponseSchema.safeParse({ ...stateBody, agents: [{ id: 'b2', letter: 'B', x: 1, y: 1, facing: 'up', hp: 100, team: 'blue' }] }).success,
    ).toBe(true);
    const selfBody = { x: 0, y: 0, facing: 'up' as const, hp: 100, alive: true, respawnAt: null, moveReadyAt: 0, fireReadyAt: 0, path: [] };
    expect(StateResponseSchema.safeParse({ ...stateBody, self: { ...selfBody, team: 'red' } }).success).toBe(true);
  });

  it('teams — ровно две строки: одна или три невалидны (спека командного боя 3.1, 5.2)', () => {
    expect(StateResponseSchema.safeParse({ ...stateBody, teams: [{ team: 'red', kills: 1 }] }).success).toBe(false);
    expect(
      StateResponseSchema.safeParse({
        ...stateBody,
        teams: [{ team: 'red', kills: 1 }, { team: 'blue', kills: 0 }, { team: 'red', kills: 2 }],
      }).success,
    ).toBe(false);
  });
});

describe('elim-поля state (спека elimination 5.2)', () => {
  it('MatchScore — счёт партий и порог победы; чужие поля невалидны', () => {
    expect(MatchScoreSchema.parse({ red: 1, blue: 0, toWin: 3 })).toEqual({ red: 1, blue: 0, toWin: 3 });
    expect(MatchScoreSchema.safeParse({ red: 1, blue: 0 }).success).toBe(false); // нет toWin
    expect(MatchScoreSchema.safeParse({ red: 1.5, blue: 0, toWin: 3 }).success).toBe(false); // счёт — целые
  });

  it('RoundResult — партия, победитель, причина, финал и очки на момент закрытия', () => {
    expect(
      RoundResultSchema.parse({ round: 3, winner: 'red', reason: 'wipe', matchOver: true, score: { red: 3, blue: 1 } }),
    ).toEqual({ round: 3, winner: 'red', reason: 'wipe', matchOver: true, score: { red: 3, blue: 1 } });
    expect(RoundResultSchema.safeParse({ round: 1, winner: 'green', reason: 'wipe', matchOver: false, score: { red: 0, blue: 0 } }).success).toBe(false);
    expect(RoundResultSchema.safeParse({ round: 1, winner: 'draw', reason: 'mercy', matchOver: false, score: { red: 0, blue: 0 } }).success).toBe(false);
  });

  it('state: matchScore и lastRoundResult — optional; lastRoundResult бывает null (до первой закрытой)', () => {
    expect(StateResponseSchema.safeParse({ ...stateBody, matchScore: { red: 1, blue: 0, toWin: 3 }, lastRoundResult: null }).success).toBe(true);
    expect(
      StateResponseSchema.safeParse({
        ...stateBody,
        matchScore: { red: 2, blue: 1, toWin: 3 },
        lastRoundResult: { round: 3, winner: 'draw', reason: 'timeout', matchOver: false, score: { red: 2, blue: 1 } },
      }).success,
    ).toBe(true);
    expect(StateResponseSchema.safeParse(stateBody).success).toBe(true); // ffa/team — полей нет вовсе
  });
});

// Админ-API веб-управления (спека веб-управления 4).
describe('админ-схемы (спека веб-управления 4)', () => {
  it('match-запрос: пустое тело и явные null валидны, неизвестные поля и дроби — нет', () => {
    expect(AdminMatchRequestSchema.parse({})).toEqual({});
    expect(
      AdminMatchRequestSchema.parse({ mode: 'elim', rounds: 2, roundKills: null, friendlyFire: null, fov: null, office: null }),
    ).toEqual({ mode: 'elim', rounds: 2, roundKills: null, friendlyFire: null, fov: null, office: null });
    expect(AdminMatchRequestSchema.safeParse({ mode: 'ctf' }).success).toBe(false);
    expect(AdminMatchRequestSchema.safeParse({ rounds: 1.5 }).success).toBe(false);
    expect(AdminMatchRequestSchema.safeParse({ map: 'x' }).success).toBe(false); // strictObject: чужое поле
  });

  it('config-ответ: null в настройках, размер битого офиса — null, ошибки списком', () => {
    const body = {
      settings: { mode: 'ffa', rounds: null, roundKills: null, friendlyFire: false, fov: 12 },
      defaults: { roundKillsFfa: 10, roundKillsTeam: 20, rounds: 3 },
      currentOffice: 'offices/local',
      offices: [
        { dir: 'offices/local', size: [40, 20], errors: [] },
        { dir: 'offices/ghost', size: null, errors: ['[io] нет файла office.yaml'] },
      ],
      bots: [{ id: 'bot1', name: 'bot1' }],
      roster: [
        { id: 'bot1', name: 'bot1', alive: true },
        { id: 'a1', name: 'Аня', alive: false, team: 'red' }, // team — optional: ffa без него, team/elim с ним
      ],
    };
    expect(AdminConfigResponseSchema.parse(body)).toBeTruthy();
    expect(AdminMatchResponseSchema.safeParse({ ...body, kicked: false }).success).toBe(true);
    expect(AdminConfigResponseSchema.safeParse({ ...body, settings: { mode: 'ffa', rounds: null, roundKills: null, friendlyFire: false } }).success).toBe(false); // нет fov
    expect(AdminConfigResponseSchema.safeParse({ ...body, roster: [{ id: 'a1', name: 'Аня', alive: true, team: 'green' }] }).success).toBe(false); // team — только red/blue
  });
});
