# retoor <retoor@molodetz.nl>

import time

import requests

from tests.api.battles._helpers import JSON, _create_war_post, _session_battles
from tests.conftest import BASE_URL


def test_listing_renders_battle_card(app_server):
    s, _ = _session_battles()
    _create_war_post(s, f"listing-{int(time.time() * 1000)}", "Vim", "Emacs")
    r = s.get(f"{BASE_URL}/battles")
    assert r.status_code == 200
    assert "dp-opinion-war" in r.text
    assert "Vim" in r.text


def test_listing_json_shape(app_server):
    s, _ = _session_battles()
    _, war = _create_war_post(s, f"json-{int(time.time() * 1000)}")
    r = s.get(f"{BASE_URL}/battles", headers=JSON)
    assert r.status_code == 200
    data = r.json()
    assert data["current_filter"] == "active"
    assert set(data["counts"]) == {"active", "ended", "mine"}
    uids = [battle["uid"] for battle in data["battles"]]
    assert war["uid"] in uids
    battle = next(b for b in data["battles"] if b["uid"] == war["uid"])
    assert battle["faction_a"] == "Tabs"
    assert battle["pct_a"] + battle["pct_b"] == 100
    assert battle["fight_cost"] > 0


def test_listing_guest_access(app_server):
    s, _ = _session_battles()
    _create_war_post(s, f"guest-{int(time.time() * 1000)}")
    r = requests.get(f"{BASE_URL}/battles")
    assert r.status_code == 200
    assert "dp-opinion-war" in r.text


def test_listing_search_matches_faction(app_server):
    s, _ = _session_battles()
    marker = f"Zx{int(time.time() * 1000) % 100000}"
    _, war = _create_war_post(s, f"search-{marker}", marker, "Others")
    r = s.get(f"{BASE_URL}/battles", params={"search": marker}, headers=JSON)
    uids = [battle["uid"] for battle in r.json()["battles"]]
    assert uids == [war["uid"]]


def test_listing_invalid_filter_falls_back(app_server):
    s, _ = _session_battles()
    r = s.get(f"{BASE_URL}/battles", params={"filter": "bogus"}, headers=JSON)
    assert r.json()["current_filter"] == "active"


def test_battle_state_json(app_server):
    s, _ = _session_battles()
    _, war = _create_war_post(s, f"state-{int(time.time() * 1000)}")
    r = requests.get(f"{BASE_URL}/battles/{war['uid']}")
    assert r.status_code == 200
    data = r.json()
    assert data["uid"] == war["uid"]
    assert data["status"] == "active"
    assert data["viewer"] is None
    assert data["ends_in"]


def test_battle_state_unknown_uid_404(app_server):
    r = requests.get(f"{BASE_URL}/battles/does-not-exist", headers=JSON)
    assert r.status_code == 404
