# retoor <retoor@molodetz.nl>

import time
from datetime import datetime, timedelta, timezone

import requests

from devplacepy.database import get_table, refresh_snapshot
from devplacepy.utils.rewards import XP_BATTLE_PART, XP_BATTLE_TOP, XP_BATTLE_WIN
from tests.api.battles._helpers import (
    _create_war_post,
    _fight,
    _join,
    _session_battles,
    _user_row,
    _war_row,
)
from tests.conftest import BASE_URL


def _warp_ended(war_uid):
    past = (datetime.now(timezone.utc) - timedelta(minutes=1)).isoformat()
    get_table("opinion_wars").update({"uid": war_uid, "ends_at": past}, ["uid"])


def test_resolution_awards_xp_exactly_once(app_server):
    s, winner_name = _session_battles()
    other, loser_name = _session_battles()
    _, war = _create_war_post(s, f"resolve-{int(time.time() * 1000)}")
    _join(s, war["uid"], "a")
    _join(other, war["uid"], "b")
    assert _fight(s, war["uid"]).status_code == 200
    winner_before = int(_user_row(winner_name)["xp"] or 0)
    loser_before = int(_user_row(loser_name)["xp"] or 0)

    _warp_ended(war["uid"])
    r = requests.get(f"{BASE_URL}/battles/{war['uid']}")
    assert r.status_code == 200
    state = r.json()
    assert state["status"] == "resolved"
    assert state["winner"] == "a"
    assert state["winner_label"] == "Tabs"

    row = _war_row(war["uid"])
    assert row["status"] == "resolved"
    assert row["resolved_at"]

    winner_after = int(_user_row(winner_name)["xp"] or 0)
    loser_after = int(_user_row(loser_name)["xp"] or 0)
    assert winner_after == winner_before + XP_BATTLE_PART + XP_BATTLE_WIN + XP_BATTLE_TOP
    assert loser_after == loser_before

    events = requests.get(f"{BASE_URL}/battles/{war['uid']}/events").json()["events"]
    results = [event for event in events if event["kind"] == "result"]
    assert len(results) == 1

    refresh_snapshot()
    notes = list(
        get_table("notifications").find(
            type="battle", user_uid=_user_row(loser_name)["uid"]
        )
    )
    assert any("Battle over" in (n.get("message") or "") for n in notes)

    r = requests.get(f"{BASE_URL}/battles/{war['uid']}")
    assert r.json()["status"] == "resolved"
    assert int(_user_row(winner_name)["xp"] or 0) == winner_after
    events = requests.get(f"{BASE_URL}/battles/{war['uid']}/events").json()["events"]
    assert len([e for e in events if e["kind"] == "result"]) == 1


def test_draw_awards_participation_only(app_server):
    s, name = _session_battles()
    _, war = _create_war_post(s, f"draw-{int(time.time() * 1000)}")
    _join(s, war["uid"], "a")
    before = int(_user_row(name)["xp"] or 0)
    _warp_ended(war["uid"])
    state = requests.get(f"{BASE_URL}/battles/{war['uid']}").json()
    assert state["winner"] == "draw"
    assert int(_user_row(name)["xp"] or 0) == before


def test_post_page_resolves_due_war(app_server):
    s, _ = _session_battles()
    post, war = _create_war_post(s, f"lazy-{int(time.time() * 1000)}")
    _join(s, war["uid"], "b")
    assert _fight(s, war["uid"]).status_code == 200
    _warp_ended(war["uid"])
    slug = post.get("slug") or post["uid"]
    r = s.get(f"{BASE_URL}/posts/{slug}")
    assert r.status_code == 200
    assert "wins the war" in r.text
    assert _war_row(war["uid"])["status"] == "resolved"
    assert _war_row(war["uid"])["winner"] == "b"
