import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { buildArenaMap, type ArenaMap } from '../src/arena-map.ts';
import { handleActions, handleJoin, handleLeave, handleMap, handleState } from '../src/api.ts';
import { FEED_LIMIT, Match, MAX_AGENTS } from '../src/game.ts';
import { JoinResponseSchema, MapInfoSchema, StateResponseSchema } from '../src/protocol.ts';

const OFFICE = readFileSync(fileURLToPath(new URL('../../../offices/local/office.yaml', import.meta.url)), 'utf8');
const CATALOG = readFileSync(fileURLToPath(new URL('../../../catalog/limezu/catalog.yaml', import.meta.url)), 'utf8');
// Один раз на файл (~90 мс каталога); ошибка загрузки валит весь файл — это и есть проверка «офис грузится».
const r = buildArenaMap(OFFICE, CATALOG);
if (!r.ok) throw new Error(`offices/local не загрузился: ${r.errors[0]!.message}`);
const arena: ArenaMap = r.value;

function makeMatch(mode?: 'ffa' | 'team' | 'elim'): Match {
  return new Match({ map: arena.map, rand: () => 0, ...(mode ? { mode } : {}) });
}

// Тройка соседних свободных клеток карты local — чтобы не хардкодить географию офиса.
// Для упора хватает первых двух; для проверки конуса враг ставится на третью (расстояние 2):
// манхэттен-сосед (расстояние 1) виден при любом взгляде (спека арены 5.1), за спиной
// не видна только клетка дальше соседней.
function freeRun(): [[number, number], [number, number], [number, number]] {
  for (let y = 0; y < arena.size[1]; y++)
    for (let x = 0; x + 2 < arena.size[0]; x++) {
      const wx = arena.origin[0] + x;
      const wy = arena.origin[1] + y;
      if (!arena.map.isBlocked(wx, wy) && !arena.map.isBlocked(wx + 1, wy) && !arena.map.isBlocked(wx + 2, wy))
        return [[wx, wy], [wx + 1, wy], [wx + 2, wy]];
    }
  throw new Error('на карте local нет тройки свободных соседей');
}

describe('составы: team в строках счёта', () => {
  it('team: строки счёта несут team, ffa — поля нет', () => {
    const tm = makeMatch('team');
    handleJoin(tm, arena, { name: 'Аня' }, 'a1');
    handleJoin(tm, arena, { name: 'Боря' }, 'b2');
    const tScore = (handleState(tm, arena, null).body as { score: { agentId: string; team?: string }[] }).score;
    expect(tScore.find((s) => s.agentId === 'a1')!.team).toBeTruthy();
    expect(tScore.find((s) => s.agentId === 'b2')!.team).toBeTruthy();
    const fm = makeMatch();
    handleJoin(fm, arena, { name: 'Аня' }, 'a1');
    const fScore = (handleState(fm, arena, null).body as { score: { agentId: string; team?: string }[] }).score;
    expect(fScore.every((s) => s.team === undefined)).toBe(true);
  });
});

describe('join (спека арены 6.1)', () => {
  it('отвечает картой, счётом и лентой, схема валидна', () => {
    const m = makeMatch();
    const r = handleJoin(m, arena, { name: 'Стас' }, 'a1f3');
    expect(r.status).toBe(200);
    expect(JoinResponseSchema.parse(r.body)).toBeTruthy();
    const body = r.body as { agentId: string; letter: string; map: { origin: number[]; siteLegend?: unknown } };
    expect(body.agentId).toBe('a1f3');
    expect(body.letter).toBe('С');
    expect(body.map.origin).toEqual([-7, -1]);
    expect(body.map.siteLegend).toBeDefined();
  });

  it('имя: trim, 1–24 кодовые точки, без управляющих — иначе 400 invalid_name', () => {
    const m = makeMatch();
    expect(handleJoin(m, arena, { name: '  Стас  ' }, 'x1').status).toBe(200); // trim по краям допустим
    expect(handleJoin(m, arena, { name: '' }, 'x2').body).toEqual({ error: 'invalid_name' });
    expect(handleJoin(m, arena, { name: '   ' }, 'x3').body).toEqual({ error: 'invalid_name' });
    expect(handleJoin(m, arena, { name: 'а'.repeat(25) }, 'x4').body).toEqual({ error: 'invalid_name' });
    expect(handleJoin(m, arena, { name: 'Стас\u0007' }, 'x5').body).toEqual({ error: 'invalid_name' });
  });

  it('дубликаты имён допустимы, различает agentId (спека арены 6.1)', () => {
    const m = makeMatch();
    expect(handleJoin(m, arena, { name: 'Стас' }, 'a1').status).toBe(200);
    expect(handleJoin(m, arena, { name: 'Стас' }, 'a2').status).toBe(200);
    expect(m.count()).toBe(2);
  });

  it('свыше 16 агентов — 400 too_many_agents (спека арены 6.1)', () => {
    const m = makeMatch();
    for (let i = 0; i < MAX_AGENTS; i++) expect(handleJoin(m, arena, { name: `игрок${i}` }, `a${i}`).status).toBe(200);
    expect(handleJoin(m, arena, { name: 'лишний' }, 'z9')).toMatchObject({ status: 400, body: { error: 'too_many_agents' } });
  });

  it('битое тело — 400 invalid_body (глобальные требования 8)', () => {
    const m = makeMatch();
    expect(handleJoin(m, arena, { name: 42 }, 'x').body).toEqual({ error: 'invalid_body' });
    expect(handleJoin(m, arena, null, 'x').body).toEqual({ error: 'invalid_body' });
  });

  it('team: просьба команды без перекоса исполняется, с перекосом — меньшая; ответ несёт team (спека командного боя 2.2, 5.1)', () => {
    const m = makeMatch('team');
    const r1 = handleJoin(m, arena, { name: 'Аня', team: 'red' }, 'a1');
    expect((r1.body as { team: string }).team).toBe('red');
    const r2 = handleJoin(m, arena, { name: 'Боря', team: 'red' }, 'a2'); // red стал бы 2:0 — перекос
    expect((r2.body as { team: string }).team).toBe('blue');
    const r3 = handleJoin(m, arena, { name: 'Вера' }, 'a3'); // без просьбы, 1:1 — red
    expect((r3.body as { team: string }).team).toBe('red');
    const r4 = handleJoin(m, arena, { name: 'Гриша' }, 'a4'); // 2:1 — меньшая blue
    expect((r4.body as { team: string }).team).toBe('blue');
    expect(JoinResponseSchema.parse(r4.body)).toBeTruthy(); // схема с team валидна
  });

  it('FFA: просьба team молча игнорируется, поля team в ответе нет (спека командного боя 4, 5.1)', () => {
    const m = makeMatch();
    const r = handleJoin(m, arena, { name: 'Стас', team: 'red' }, 'a1');
    expect(r.status).toBe(200);
    expect((r.body as Record<string, unknown>)['team']).toBeUndefined();
    expect(JoinResponseSchema.parse(r.body)).toBeTruthy();
  });
});

describe('map (спека ботов 3.1)', () => {
  it('статика карты без join — та же схема, что map в join', () => {
    const r = handleMap(arena);
    expect(r.status).toBe(200);
    expect(MapInfoSchema.parse(r.body)).toBeTruthy();
    const join = handleJoin(makeMatch(), arena, { name: 'зритель' }, 'a1f3');
    expect((join.body as { map: unknown }).map).toEqual(r.body);
  });
});

describe('state (спека арены 6.2)', () => {
  it('неизвестный агент — 404 unknown_agent', () => {
    const m = makeMatch();
    expect(handleState(m, arena, 'ghost')).toMatchObject({ status: 404, body: { error: 'unknown_agent' } });
  });

  it('агент: self, видимость фильтрует чужих и снаряды, lastRejected на месте', () => {
    const m = makeMatch();
    handleJoin(m, arena, { name: 'Стас' }, 'a1');
    const [p, , far] = freeRun();
    const me = m.agent('a1')!;
    me.x = p[0];
    me.y = p[1];
    me.facing = 'left';
    handleJoin(m, arena, { name: 'Боря' }, 'b2');
    const enemy = m.agent('b2')!;
    enemy.x = far[0]; // на 2 правее меня — за спиной при взгляде left (сосед на 1 клетку виден всегда)
    enemy.y = far[1];
    m.step();
    const r = handleState(m, arena, 'a1');
    expect(r.status).toBe(200);
    const body = StateResponseSchema.parse(r.body);
    expect(body.self!.alive).toBe(true);
    expect(body.visibleCells!.length).toBeGreaterThan(0);
    expect(body.agents.map((u) => u.id)).not.toContain('b2'); // за спиной не видно
    expect(body.lastRejected).toBeNull();

    me.facing = 'right';
    const r2 = handleState(m, arena, 'a1');
    const body2 = StateResponseSchema.parse(r2.body);
    expect(body2.agents.map((u) => u.id)).toContain('b2'); // повернулся — увидел
  });

  it('наблюдатель без agent: все агенты, без self/visibleCells/lastRejected (спека арены 6.4)', () => {
    const m = makeMatch();
    handleJoin(m, arena, { name: 'Стас' }, 'a1');
    handleJoin(m, arena, { name: 'Боря' }, 'b2');
    const body = handleState(m, arena, null).body as Record<string, unknown>;
    expect((body['agents'] as unknown[]).length).toBe(2);
    expect('self' in body).toBe(false);
    expect('visibleCells' in body).toBe(false);
    expect('lastRejected' in body).toBe(false);
    expect(StateResponseSchema.parse(body)).toBeTruthy();
  });

  it('лента — последние 20 (спека арены 6.2)', () => {
    const m = makeMatch();
    const [p, q] = freeRun();
    handleJoin(m, arena, { name: 'Стас' }, 'k');
    const killer = m.agent('k')!;
    handleJoin(m, arena, { name: 'Боря' }, 'v');
    const victim = m.agent('v')!;
    killer.x = p[0];
    killer.y = p[1];
    for (let i = 0; i < 25; i++) {
      // каждую итерацию возвращать обоих в упор: респауны и новые партии (после 10-го и 20-го
      // фрага) раскидывают агентов по карте
      killer.x = p[0];
      killer.y = p[1];
      killer.facing = 'right';
      victim.x = q[0];
      victim.y = q[1];
      victim.hp = 25;
      m.actions('k', [{ type: 'fire' }]);
      m.step(); // упор: жертва гибнет
      for (let s = 0; s < 62; s++) m.step(); // респаун жертвы
    }
    const body = handleState(m, arena, null).body as { feed: unknown[] };
    expect(body.feed.length).toBe(FEED_LIMIT);
  });

  it('счёт — по убыванию K/D: без смертей ratio = фраги, равный ratio — больше фрагов выше, дальше порядок id', () => {
    const m = makeMatch();
    handleJoin(m, arena, { name: 'Аня' }, 'a1');
    handleJoin(m, arena, { name: 'Борис' }, 'a2');
    handleJoin(m, arena, { name: 'Вера' }, 'a3');
    handleJoin(m, arena, { name: 'Гоша' }, 'a4');
    handleJoin(m, arena, { name: 'Денис' }, 'a5');
    const kd = (id: string, kills: number, deaths: number): void => {
      const a = m.agent(id)!;
      a.kills = kills;
      a.deaths = deaths;
    };
    kd('a1', 2, 0); // ratio 2 без смертей
    kd('a2', 4, 2); // ratio 2 — фрагов больше, стоит выше Ани
    kd('a3', 1, 1); // ratio 1
    kd('a4', 0, 0); // ratio 0
    kd('a5', 0, 3); // ratio 0 — фраги равны, порядок id (стабильная сортировка)
    const st = handleState(m, arena, null).body as { score: { agentId: string }[] };
    expect(st.score.map((s) => s.agentId)).toEqual(['a2', 'a1', 'a3', 'a4', 'a5']);
  });

  it('state.tournament — накопитель завершённых партий по K/D, у игрока и зрителя (спека турнирной таблицы 2.1)', () => {
    const m = new Match({ map: arena.map, rand: () => 0, idleLeaveMs: Infinity }); // 5 минут тиков без запросов — молчуны не тема
    handleJoin(m, arena, { name: 'Аня' }, 'a1');
    handleJoin(m, arena, { name: 'Борис' }, 'a2');
    const a1 = m.agent('a1')!;
    const a2 = m.agent('a2')!;
    a1.kills = 3;
    a1.deaths = 1; // партия 1: Аня 3/1, Борис 1/3
    a2.kills = 1;
    a2.deaths = 3;
    for (let i = 0; i < 6001; i++) m.step(); // партия закрыта по времени — накопитель снят до сброса
    a1.kills = 7; // текущая партия 2 в накопитель не входит
    const spectator = handleState(m, arena, null).body as { tournament: { agentId: string; kills: number }[] };
    expect(spectator.tournament).toEqual([
      { agentId: 'a1', name: 'Аня', letter: 'А', kills: 3, deaths: 1 },
      { agentId: 'a2', name: 'Борис', letter: 'Б', kills: 1, deaths: 3 },
    ]);
    const player = handleState(m, arena, 'a2').body as { tournament: unknown };
    expect(player.tournament).toEqual(spectator.tournament);
    expect(StateResponseSchema.parse(handleState(m, arena, 'a2').body)).toBeTruthy();
  });

  it('team: teams сверху, team у агентов и self; зритель получает то же (спека командного боя 5.2)', () => {
    const m = makeMatch('team');
    handleJoin(m, arena, { name: 'Аня' }, 'a1'); // первый — red
    handleJoin(m, arena, { name: 'Боря' }, 'a2'); // второй — blue
    const spect = handleState(m, arena, null).body as {
      teams: { team: string; kills: number }[];
      agents: { team?: string }[];
    };
    expect(spect.teams).toEqual([
      { team: 'red', kills: 0 },
      { team: 'blue', kills: 0 },
    ]);
    expect(spect.agents.map((u) => u.team).sort()).toEqual(['blue', 'red']);
    expect(StateResponseSchema.parse(spect)).toBeTruthy();
    const me = handleState(m, arena, 'a1').body as { self?: { team?: string } };
    expect(me.self!.team).toBe('red');
    expect(StateResponseSchema.parse(me)).toBeTruthy();
  });

  it('elim: matchScore и lastRoundResult — null до первой закрытой, очко после; зритель получает то же (спека elimination 5.2)', () => {
    const m = new Match({ map: arena.map, rand: () => 0, idleLeaveMs: Infinity, mode: 'elim' }); // минуты тиков — молчуны не тема
    handleJoin(m, arena, { name: 'Аня', team: 'red' }, 'a1');
    handleJoin(m, arena, { name: 'Боря', team: 'blue' }, 'b2');
    const before = handleState(m, arena, null).body as { matchScore?: unknown; lastRoundResult: unknown };
    expect(before.matchScore).toEqual({ red: 0, blue: 0, toWin: 3 });
    expect(before.lastRoundResult).toBeNull();
    expect(StateResponseSchema.parse(before)).toBeTruthy();
    const [p, q] = freeRun(); // вайп: Аня убивает Борю в упор
    const a1 = m.agent('a1')!;
    const b2 = m.agent('b2')!;
    a1.x = p[0];
    a1.y = p[1];
    a1.facing = 'right';
    b2.x = q[0];
    b2.y = q[1];
    b2.hp = 25;
    m.actions('a1', [{ type: 'fire' }]);
    m.step(); // партия закрыта вайпом
    const after = handleState(m, arena, null).body as {
      matchScore: { red: number; blue: number; toWin: number };
      lastRoundResult: { round: number; winner: string; reason: string; matchOver: boolean; score: { red: number; blue: number } };
    };
    expect(after.matchScore).toEqual({ red: 1, blue: 0, toWin: 3 });
    expect(after.lastRoundResult).toEqual({ round: 1, winner: 'red', reason: 'wipe', matchOver: false, score: { red: 1, blue: 0 } });
    expect(StateResponseSchema.parse(after)).toBeTruthy();
    const me = handleState(m, arena, 'a1').body as { matchScore: unknown; lastRoundResult: unknown };
    expect(me.matchScore).toEqual(after.matchScore); // игрок получает то же
    expect(me.lastRoundResult).toEqual(after.lastRoundResult);
  });

  it('elim: финал матча — matchOver и финальный score, счёт обнулён (спека elimination 3.6, 5.2)', () => {
    const m = new Match({ map: arena.map, rand: () => 0, idleLeaveMs: Infinity, mode: 'elim', roundsToWin: 1 });
    handleJoin(m, arena, { name: 'Аня', team: 'red' }, 'a1');
    handleJoin(m, arena, { name: 'Боря', team: 'blue' }, 'b2');
    const [p, q] = freeRun(); // вайп: Аня убивает Борю в упор
    const a1 = m.agent('a1')!;
    const b2 = m.agent('b2')!;
    a1.x = p[0];
    a1.y = p[1];
    a1.facing = 'right';
    b2.x = q[0];
    b2.y = q[1];
    b2.hp = 25;
    m.actions('a1', [{ type: 'fire' }]);
    m.step(); // roundsToWin 1 — первая же партия закрывает матч
    const body = handleState(m, arena, null).body as {
      matchScore: { red: number; blue: number; toWin: number };
      lastRoundResult: { matchOver: boolean; score: { red: number; blue: number } };
    };
    expect(body.lastRoundResult).toEqual({ round: 1, winner: 'red', reason: 'wipe', matchOver: true, score: { red: 1, blue: 0 } });
    expect(body.matchScore).toEqual({ red: 0, blue: 0, toWin: 1 }); // матч закрыт — счёт в ноль
    expect(StateResponseSchema.parse(body)).toBeTruthy();
  });

  it('ffa и team: полей matchScore/lastRoundResult в state нет (спека elimination 5.2)', () => {
    for (const mode of ['ffa', 'team'] as const) {
      const m = makeMatch(mode);
      handleJoin(m, arena, { name: 'Вера' }, 'v1');
      const body = handleState(m, arena, null).body as Record<string, unknown>;
      expect('matchScore' in body).toBe(false);
      expect('lastRoundResult' in body).toBe(false);
    }
  });

  it('elim: team в join-ответе и у агентов — как в team, state.teams нет (спека elimination 5.1)', () => {
    const m = makeMatch('elim');
    const r = handleJoin(m, arena, { name: 'Аня', team: 'red' }, 'a1');
    expect((r.body as { team: string }).team).toBe('red');
    handleJoin(m, arena, { name: 'Боря', team: 'blue' }, 'b2');
    const spect = handleState(m, arena, null).body as Record<string, unknown> & { agents: { team?: string }[] };
    expect('teams' in spect).toBe(false); // командные фраги — поле team-режима
    expect(spect.agents.map((u) => u.team).sort()).toEqual(['blue', 'red']);
    expect(StateResponseSchema.parse(spect)).toBeTruthy();
  });

  it('FFA: в state нет ни teams, ни team у агентов и self (спека командного боя 5.2)', () => {
    const m = makeMatch();
    handleJoin(m, arena, { name: 'Вера' }, 'v1');
    const spect = handleState(m, arena, null).body as Record<string, unknown>;
    expect('teams' in spect).toBe(false);
    expect('team' in (spect['agents'] as Record<string, unknown>[])[0]!).toBe(false);
    const me = handleState(m, arena, 'v1').body as { self?: Record<string, unknown> };
    expect(me.self !== undefined && 'team' in me.self).toBe(false);
  });
});

describe('actions (спека арены 6.3)', () => {
  it('пустой список и нормальные действия — 204', () => {
    const m = makeMatch();
    handleJoin(m, arena, { name: 'Стас' }, 'a1');
    expect(handleActions(m, { agentId: 'a1', actions: [] })).toMatchObject({ status: 204 });
    expect(handleActions(m, { agentId: 'a1', actions: [{ type: 'move', dir: 'up' }] })).toMatchObject({ status: 204 });
  });

  it('неизвестный агент — 404, битая схема — 400 invalid_body', () => {
    const m = makeMatch();
    expect(handleActions(m, { agentId: 'ghost', actions: [] })).toMatchObject({ status: 404, body: { error: 'unknown_agent' } });
    expect(handleActions(m, { agentId: 'ghost', actions: [{ type: 'jump' }] })).toMatchObject({ status: 400, body: { error: 'invalid_body' } });
    expect(handleActions(m, { agentId: 'ghost' })).toMatchObject({ status: 400, body: { error: 'invalid_body' } });
  });
});

describe('leave (спека арены 6.5)', () => {
  it('204: агент уходит из матча и счёта; повторный — 404 unknown_agent', () => {
    const m = makeMatch();
    handleJoin(m, arena, { name: 'Стас' }, 'a1f3');
    expect(handleLeave(m, { agentId: 'a1f3' })).toMatchObject({ status: 204 });
    const st = handleState(m, arena, null);
    expect((st.body as { score: unknown[] }).score).toEqual([]);
    expect(handleState(m, arena, 'a1f3')).toMatchObject({ status: 404, body: { error: 'unknown_agent' } });
    expect(handleLeave(m, { agentId: 'a1f3' })).toMatchObject({ status: 404, body: { error: 'unknown_agent' } });
  });

  it('битое тело — 400 invalid_body', () => {
    const m = makeMatch();
    expect(handleLeave(m, null)).toMatchObject({ status: 400, body: { error: 'invalid_body' } });
    expect(handleLeave(m, {})).toMatchObject({ status: 400, body: { error: 'invalid_body' } });
  });

  it('опрос state — сердцебиение: продлевает присутствие агента (спека арены 6.5)', () => {
    const m = makeMatch();
    handleJoin(m, arena, { name: 'Стас' }, 'a1f3');
    for (let i = 0; i < 3; i++) m.step(); // t = 150
    const a = m.agent('a1f3')!;
    a.lastSeenAt = 0; // состарили сердце — как минуту назад
    handleState(m, arena, 'a1f3');
    expect(a.lastSeenAt).toBe(m.t);
  });
});
