package main

// Клиентская половина protocol.ts (спека §4): структуры вместо zod-схем, без отдельной валидации —
// клиент доверяет серверу. Указатели — у всех полей, опциональных или nullable в схемах:
// «поля нет» и «null» дают одинаковый nil, клиенту этого достаточно (спека §4).

import "bytes"
import "encoding/json"

// Направления арены — 8 (спека диагоналей 3.1); команды team-режима — две (спека командного боя 3.1).
type Dir string
type Team string

// Действия адаптера (спека арены 6.3). Поле type — не поле структуры: у строкового поля в Go нет
// дефолта, литерал MoveAction{Dir: …} отправил бы "type":"" — серверная zod-схема
// (discriminatedUnion по type) отвергла бы каждое действие invalid_body. Поэтому type — константа
// каждого типа, появляющаяся в MarshalJSON; порядок ключей — байт-в-байт как литералы TS
// (спека §2 п.6), маршализатор — marshalAction с SetEscapeHTML(false).
type Action interface{ isAction() }

type MoveAction struct {
	Dir Dir `json:"dir"`
}

type TurnAction struct {
	Facing Dir `json:"facing"`
}

type FireAction struct{}

type MoveToAction struct {
	X int64 `json:"x"`
	Y int64 `json:"y"`
}

func (MoveAction) isAction()   {}
func (TurnAction) isAction()   {}
func (FireAction) isAction()   {}
func (MoveToAction) isAction() {}

// MarshalJSON — тип действия первым ключом, дальше поля в порядке литерала TS
// ({ type, dir }, { type, facing }, { type }, { type, x, y }).
func (a MoveAction) MarshalJSON() ([]byte, error) {
	return marshalCompact(struct {
		Type string `json:"type"`
		Dir  Dir    `json:"dir"`
	}{"move", a.Dir})
}

func (a TurnAction) MarshalJSON() ([]byte, error) {
	return marshalCompact(struct {
		Type   string `json:"type"`
		Facing Dir    `json:"facing"`
	}{"turn", a.Facing})
}

func (a FireAction) MarshalJSON() ([]byte, error) {
	return marshalCompact(struct {
		Type string `json:"type"`
	}{"fire"})
}

func (a MoveToAction) MarshalJSON() ([]byte, error) {
	return marshalCompact(struct {
		Type string `json:"type"`
		X    int64  `json:"x"`
		Y    int64  `json:"y"`
	}{"moveTo", a.X, a.Y})
}

// marshalAction — компактный JSON без HTML-экранирования: json.Marshal заэкранировал бы <, >, &
// в <…, чего JSON.stringify не делает (решение плана 7).
func marshalAction(a Action) ([]byte, error) { return marshalCompact(a) }

// encodeBody — то же для тел запросов (join/actions/leave) и JSON-подписей (render.go): any.
func encodeBody(v any) ([]byte, error) { return marshalCompact(v) }

// marshalCompact — общий энкодер: json.Encoder с SetEscapeHTML(false), хвостовой \n срезается.
func marshalCompact(v any) ([]byte, error) {
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.SetEscapeHTML(false)
	if err := enc.Encode(v); err != nil {
		return nil, err
	}
	return bytes.TrimRight(buf.Bytes(), "\n"), nil
}

// Карта (MapInfoSchema): клетки — символы легенды, walkable — 0/1, building — [x, y, w, h].
type MapInfo struct {
	Origin     [2]int64           `json:"origin"`
	Size       [2]int64           `json:"size"`
	Cells      [][]string         `json:"cells"`
	Walkable   [][]int64          `json:"walkable"`
	Building   [4]int64           `json:"building"`
	Legend     map[string]string  `json:"legend"`
	SiteLegend *map[string]string `json:"siteLegend"` // без участка поля нет (спека арены 6.1)
}

type ScoreRow struct {
	AgentID string `json:"agentId"`
	Name    string `json:"name"`
	Letter  string `json:"letter"`
	Kills   int64  `json:"kills"`
	Deaths  int64  `json:"deaths"`
	Alive   bool   `json:"alive"`
	Team    *Team  `json:"team"` // команда строки — только в team/elim: цвет буквы в блоке счёта (составы)
}

// Строка командного счёта (спека командного боя 5.2) — только в team-режиме; порядок red, blue.
type TeamScore struct {
	Team  Team  `json:"team"`
	Kills int64 `json:"kills"`
}

// Счёт партий elim-матча (спека elimination 5.2) — только в elim.
type MatchScore struct {
	Red   int64 `json:"red"`
	Blue  int64 `json:"blue"`
	ToWin int64 `json:"toWin"`
}

// Исход последней закрытой elim-партии (спека elimination 3.6, 5.2); до первой — null.
type RoundResult struct {
	Round     int64  `json:"round"`
	Winner    string `json:"winner"` // red | blue | draw
	Reason    string `json:"reason"` // wipe | timeout
	MatchOver bool   `json:"matchOver"`
	Score     struct {
		Red  int64 `json:"red"`
		Blue int64 `json:"blue"`
	} `json:"score"`
}

type FeedItem struct {
	T      int64  `json:"t"`
	Round  int64  `json:"round"`
	Killer string `json:"killer"`
	Victim string `json:"victim"`
}

// Накопитель завершённых партий (спека турнирной таблицы 2.1): место — индекс строки + 1.
type TournamentRow struct {
	AgentID string `json:"agentId"`
	Name    string `json:"name"`
	Letter  string `json:"letter"`
	Kills   int64  `json:"kills"`
	Deaths  int64  `json:"deaths"`
}

// Чужой агент: поле alive не отдаётся — мёртвых в agents нет (решение плана 13 арены).
type AgentPublic struct {
	ID     string `json:"id"`
	Letter string `json:"letter"`
	Team   *Team  `json:"team"` // команда — только в team-режиме (спека командного боя 5.2)
	X      int64  `json:"x"`
	Y      int64  `json:"y"`
	Facing Dir    `json:"facing"`
	HP     int64  `json:"hp"`
}

// Своё состояние: respawnAt nullable — *int64, null («ждём следующей партии») и число
// («респаун через N с») различаются как nil и не-nil (спека §4, elimination 6.2).
type SelfState struct {
	X           int64      `json:"x"`
	Y           int64      `json:"y"`
	Facing      Dir        `json:"facing"`
	HP          int64      `json:"hp"`
	Alive       bool       `json:"alive"`
	RespawnAt   *int64     `json:"respawnAt"`
	MoveReadyAt int64      `json:"moveReadyAt"`
	FireReadyAt int64      `json:"fireReadyAt"`
	Path        [][2]int64 `json:"path"`
	Team        *Team      `json:"team"` // своя команда — только в team-режиме
}

type Projectile struct {
	X  int64 `json:"x"`
	Y  int64 `json:"y"`
	DX int64 `json:"dx"`
	DY int64 `json:"dy"`
}

type StateResponse struct {
	T               int64           `json:"t"`
	Round           int64           `json:"round"`
	Teams           *[]TeamScore    `json:"teams"`           // только team-режим
	MatchScore      *MatchScore     `json:"matchScore"`      // только elim
	LastRoundResult *RoundResult    `json:"lastRoundResult"` // только elim; до первой партии — null
	Self            *SelfState      `json:"self"`
	VisibleCells    *[][2]int64     `json:"visibleCells"` // nil — наблюдатель (без agent в запросе)
	Agents          []AgentPublic   `json:"agents"`
	Projectiles     []Projectile    `json:"projectiles"`
	Score           []ScoreRow      `json:"score"`
	Tournament      []TournamentRow `json:"tournament"`
	Feed            []FeedItem      `json:"feed"`
	LastRejected    *struct {       // null/отсутствие — nil
		Type   string `json:"type"`
		Reason string `json:"reason"`
	} `json:"lastRejected"`
}

type JoinResponse struct {
	AgentID string     `json:"agentId"`
	Letter  string     `json:"letter"`
	Team    *Team      `json:"team"` // команда вошедшего — только в team-режиме
	Map     MapInfo    `json:"map"`
	Score   []ScoreRow `json:"score"`
	Feed    []FeedItem `json:"feed"`
}
