package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"
)

// HTTP-обвязка клиента (спека §2 п.6): join/actions/leave/map — те же запросы, что шлёт
// TS-клиент; кадры состояния идут каналом WS (ws.go, спека push 3). Таймауты как в TS:
// только leave — 500 мс, остальные — без явного таймаута.

var httpClient = &http.Client{} // без таймаута, как fetch в TS

var httpLeaveClient = &http.Client{Timeout: 500 * time.Millisecond}

// postJSON — POST с телом application/json (без HTML-экранирования — решение плана 7).
func postJSON(client *http.Client, u string, body []byte) (*http.Response, error) {
	req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("content-type", "application/json")
	return client.Do(req)
}

// Join — POST /v1/arena/join телом { name } (спека арены 6.1).
func Join(base *url.URL, name string) (JoinResponse, error) {
	var me JoinResponse
	body, err := encodeBody(struct {
		Name string `json:"name"`
	}{name})
	if err != nil {
		return me, err
	}
	res, err := postJSON(httpClient, joinURL(base, "/v1/arena/join"), body)
	if err != nil {
		return me, err
	}
	defer res.Body.Close()
	if res.StatusCode >= 400 {
		text, _ := io.ReadAll(res.Body)
		return me, fmt.Errorf("join: %d %s", res.StatusCode, text)
	}
	return me, json.NewDecoder(res.Body).Decode(&me)
}

// rejectedError — 4xx/5xx от /v1/arena/actions: клиент печатает «действие отклонено: N».
type rejectedError struct{ status int }

func (e rejectedError) Error() string {
	return fmt.Sprintf("действие отклонено: %d", e.status)
}

func IsRejected(err error) bool {
	var r rejectedError
	return errors.As(err, &r)
}

// SendActions — POST /v1/arena/actions телом { agentId, actions } (спека арены 6.3); пустой
// список не отправляется вовсе — фильтрует вызывающий, как send() в TS.
func SendActions(base *url.URL, agentID string, actions []Action) error {
	body, err := encodeBody(struct {
		AgentID string   `json:"agentId"`
		Actions []Action `json:"actions"`
	}{agentID, actions})
	if err != nil {
		return err
	}
	res, err := postJSON(httpClient, joinURL(base, "/v1/arena/actions"), body)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode >= 400 {
		return rejectedError{res.StatusCode}
	}
	return nil
}

// Leave — POST /v1/arena/leave телом { agentId }, таймаут 500 мс: сервер недоступен —
// выходим и без прощания (спека арены 6.5).
func Leave(base *url.URL, agentID string) error {
	body, err := encodeBody(struct {
		AgentID string `json:"agentId"`
	}{agentID})
	if err != nil {
		return err
	}
	res, err := postJSON(httpLeaveClient, joinURL(base, "/v1/arena/leave"), body)
	if err != nil {
		return err
	}
	res.Body.Close()
	return nil
}

// FetchMap — GET /v1/arena/map: статика карты для зрителя без join (спека ботов 3.1).
func FetchMap(base *url.URL) (MapInfo, error) {
	var m MapInfo
	res, err := httpClient.Get(joinURL(base, "/v1/arena/map"))
	if err != nil {
		return m, err
	}
	defer res.Body.Close()
	if res.StatusCode >= 400 {
		text, _ := io.ReadAll(res.Body)
		return m, fmt.Errorf("карта: %d %s", res.StatusCode, text)
	}
	return m, json.NewDecoder(res.Body).Decode(&m)
}

// joinURL — new URL(path, base) из TS: абсолютный путь заменяет путь базы.
func joinURL(base *url.URL, path string) string {
	ref, _ := url.Parse(path)
	return base.ResolveReference(ref).String()
}
