"""Tests for the game time system."""

import time

import pytest

from mudlib.gametime import GameTime, get_game_day, get_game_hour, init_game_time


@pytest.fixture(autouse=True)
def _reset_globals():
    yield
    import mudlib.gametime

    mudlib.gametime._game_time = None


def test_get_game_hour_at_epoch():
    """Game hour should be 0 at epoch."""
    epoch = time.time()
    gt = GameTime(epoch, real_minutes_per_game_hour=1.0)
    assert gt.get_game_hour() == 0


def test_get_game_hour_after_one_hour():
    """Game hour should advance after one real minute."""
    epoch = time.time() - 60  # one real minute ago
    gt = GameTime(epoch, real_minutes_per_game_hour=1.0)
    assert gt.get_game_hour() == 1


def test_get_game_hour_wraps_at_24():
    """Game hour should wrap from 23 back to 0."""
    epoch = time.time() - (24 * 60)  # 24 real minutes ago
    gt = GameTime(epoch, real_minutes_per_game_hour=1.0)
    assert gt.get_game_hour() == 0


def test_get_game_day_at_epoch():
    """Game day should be 0 at epoch."""
    epoch = time.time()
    gt = GameTime(epoch, real_minutes_per_game_hour=1.0)
    assert gt.get_game_day() == 0


def test_get_game_day_after_24_hours():
    """Game day should be 1 after 24 game hours."""
    epoch = time.time() - (24 * 60)  # 24 real minutes ago = 24 game hours
    gt = GameTime(epoch, real_minutes_per_game_hour=1.0)
    assert gt.get_game_day() == 1


def test_get_game_day_after_48_hours():
    """Game day should be 2 after 48 game hours."""
    epoch = time.time() - (48 * 60)  # 48 real minutes ago
    gt = GameTime(epoch, real_minutes_per_game_hour=1.0)
    assert gt.get_game_day() == 2


def test_get_game_day_partial_day():
    """Game day should not increment until 24 hours have passed."""
    epoch = time.time() - (12 * 60)  # 12 real minutes ago = 12 game hours
    gt = GameTime(epoch, real_minutes_per_game_hour=1.0)
    assert gt.get_game_day() == 0


def test_global_get_game_hour():
    """Global get_game_hour should work after init."""
    init_game_time(epoch=time.time(), real_minutes_per_game_hour=1.0)
    hour = get_game_hour()
    assert 0 <= hour <= 23


def test_global_get_game_day():
    """Global get_game_day should work after init."""
    init_game_time(epoch=time.time(), real_minutes_per_game_hour=1.0)
    day = get_game_day()
    assert day >= 0


def test_global_get_game_day_raises_if_not_initialized():
    """Global get_game_day should raise if not initialized."""
    import mudlib.gametime

    # reset global state
    mudlib.gametime._game_time = None

    with pytest.raises(RuntimeError, match="Game time not initialized"):
        get_game_day()
