"""Tests: daily_new_risk_used resets only once per day, not on every run."""
from __future__ import annotations

import datetime as dt
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from apps.paper_trader.state import SessionRow, SessionStateRow, StateManager


@pytest.fixture()
def state_manager(tmp_path):
    return StateManager(tmp_path / "test.db")


@pytest.fixture()
def session(state_manager: StateManager) -> SessionRow:
    sid = state_manager.create_session("test", "configs/test.json", 10000.0)
    return state_manager.get_session(sid)


class TestDailyRiskReset:
    def test_first_call_resets_risk_used(self, state_manager: StateManager, session: SessionRow):
        """First run of the day resets daily_new_risk_used from a prior-day value."""
        # Simulate prior day had used risk
        ss = state_manager.get_session_state(session.session_id)
        ss.daily_new_risk_used = 0.5
        ss.last_processed_date = "2026-04-23"  # yesterday
        state_manager.update_session_state(ss)

        # Direct test of the guard logic
        today = dt.date(2026, 4, 24)
        ss = state_manager.get_session_state(session.session_id)
        if ss.last_processed_date != today.isoformat():
            ss.daily_new_risk_used = 0.0
        assert ss.daily_new_risk_used == 0.0

    def test_same_day_second_call_preserves_risk_used(
        self, state_manager: StateManager, session: SessionRow
    ):
        """Second call on same day must NOT reset daily_new_risk_used."""
        today = dt.date(2026, 4, 24)

        # Simulate: run_open already ran today, used 0.3 risk
        ss = state_manager.get_session_state(session.session_id)
        ss.daily_new_risk_used = 0.3
        ss.last_processed_date = today.isoformat()
        state_manager.update_session_state(ss)

        # Simulate second call (e.g., run_close later in same day)
        ss = state_manager.get_session_state(session.session_id)
        if ss.last_processed_date != today.isoformat():
            ss.daily_new_risk_used = 0.0
        # Value must be preserved
        assert ss.daily_new_risk_used == pytest.approx(0.3)

    def test_new_day_clears_risk(self, state_manager: StateManager, session: SessionRow):
        """Next calendar day's run resets the counter."""
        ss = state_manager.get_session_state(session.session_id)
        ss.daily_new_risk_used = 0.4
        ss.last_processed_date = "2026-04-24"
        state_manager.update_session_state(ss)

        today = dt.date(2026, 4, 25)
        ss = state_manager.get_session_state(session.session_id)
        if ss.last_processed_date != today.isoformat():
            ss.daily_new_risk_used = 0.0
        assert ss.daily_new_risk_used == 0.0
