"""Integration tests for work/trade balance system.

Tests the decision-making between trading and learning based on economic status.
"""

import pytest
from datetime import datetime

from openclaw.core.work_trade_balance import (
    WorkTradeBalance,
    ActivityDecision,
    WorkTradeConfig,
)
from openclaw.core.economy import TradingEconomicTracker, SurvivalStatus


class TestWorkTradeBalanceIntegration:
    """Integration tests for work/trade balance."""

    def test_work_trade_balance_initialization(self):
        """Test work/trade balance can be initialized."""
        tracker = TradingEconomicTracker(agent_id="test_trader")
        balance = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
        )

        assert balance.agent_id == "test_trader"
        assert balance.economic_tracker == tracker

    def test_thriving_status_decision(self):
        """Test decision when agent is thriving."""
        tracker = TradingEconomicTracker(agent_id="test_trader")
        # Make agent thriving (balance > 1.5x initial)
        tracker.record_income(2000.0, "test")

        balance = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
        )

        decision = balance.decide_activity()
        # Thriving: should allow both trade and learn
        assert decision.decision in [
            ActivityDecision.TRADE,
            ActivityDecision.LEARN,
        ]

    def test_critical_status_decision(self):
        """Test decision when agent is critical."""
        tracker = TradingEconomicTracker(agent_id="test_trader")
        # Critical status - very low balance
        balance = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
        )

        decision = balance.decide_activity()
        # Critical: should only allow minimal trade
        assert decision.decision in [
            ActivityDecision.MINIMAL_TRADE,
            ActivityDecision.PAPER_TRADE,
        ]

    def test_struggling_status_limits_trading(self):
        """Test that struggling status limits trading."""
        tracker = TradingEconomicTracker(agent_id="test_trader")
        # Low balance but not critical
        tracker.record_income(300.0, "test")  # 30% of initial

        balance = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
        )

        decision = balance.decide_activity()
        intensity = balance.get_trade_intensity()

        # Should have reduced position size
        assert intensity.position_size_multiplier <= 0.5

    def test_skill_level_affects_learning_priority(self):
        """Test that low skill increases learning priority."""
        tracker = TradingEconomicTracker(agent_id="test_trader")
        tracker.record_income(1500.0, "test")  # Good balance

        balance = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
            skill_level=0.2,  # Low skill
        )

        decision = balance.decide_activity()
        # Low skill should increase learning probability
        assert decision is not None

    def test_win_rate_affects_trade_intensity(self):
        """Test that win rate affects trade intensity."""
        tracker = TradingEconomicTracker(agent_id="test_trader")
        tracker.record_income(1500.0, "test")

        # High win rate
        balance_high = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
            win_rate=0.8,
        )

        # Low win rate
        balance_low = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
            win_rate=0.3,
        )

        intensity_high = balance_high.get_trade_intensity()
        intensity_low = balance_low.get_trade_intensity()

        # Higher win rate should allow more positions
        assert intensity_high.max_concurrent_positions >= intensity_low.max_concurrent_positions


class TestEconomicStatusTransitions:
    """Tests for economic status transitions affecting decisions."""

    def test_bankrupt_status_blocks_all_trading(self):
        """Test that bankrupt status blocks all trading."""
        tracker = TradingEconomicTracker(agent_id="test_trader")

        balance = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
        )

        # Simulate bankrupt status
        tracker.current_balance = -100.0

        decision = balance.decide_activity()
        # Bankrupt: no trading allowed
        assert decision.decision != ActivityDecision.TRADE

    def test_trade_intensity_by_status(self):
        """Test trade intensity varies by economic status."""
        tracker = TradingEconomicTracker(agent_id="test_trader")

        balance = WorkTradeBalance(
            agent_id="test_trader",
            economic_tracker=tracker,
        )

        # Test different balance levels
        test_cases = [
            (2000.0, "thriving"),   # > 150%
            (1000.0, "stable"),      # 100%
            (400.0, "struggling"),   # 40%
        ]

        for test_balance, expected_status in test_cases:
            tracker.current_balance = test_balance
            intensity = balance.get_trade_intensity()

            assert intensity is not None
            assert intensity.position_size_multiplier > 0


class TestWorkTradeConfig:
    """Tests for work/trade configuration."""

    def test_default_config(self):
        """Test default configuration."""
        config = WorkTradeConfig()

        assert config.thriving_weights is not None
        assert config.stable_weights is not None
        assert config.struggling_weights is not None

    def test_custom_config(self):
        """Test custom configuration."""
        config = WorkTradeConfig(
            thriving_weights={"trade": 0.8, "learn": 0.2},
            stable_weights={"trade": 0.9, "learn": 0.1},
        )

        assert config.thriving_weights["trade"] == 0.8
        assert config.thriving_weights["learn"] == 0.2
