"""Integration tests for LangGraph workflow.

Tests the complete trading workflow with all agents.
"""

import pytest
from datetime import datetime
from typing import Dict, Any

from openclaw.workflow.trading_workflow import TradingWorkflow
from openclaw.workflow.state import TradingWorkflowState, create_initial_state
from openclaw.core.economy import TradingEconomicTracker


class TestTradingWorkflowIntegration:
    """Integration tests for the complete trading workflow."""

    def test_workflow_initialization(self):
        """Test workflow can be initialized."""
        workflow = TradingWorkflow(
            symbol="AAPL",
            initial_capital=1000.0,
            enable_parallel=True
        )
        assert workflow.symbol == "AAPL"
        assert workflow.initial_capital == 1000.0
        assert workflow.enable_parallel is True

    def test_initial_state_creation(self):
        """Test initial state is created correctly."""
        state = create_initial_state(symbol="TSLA", initial_capital=500.0)
        assert state["symbol"] == "TSLA"
        assert state["initial_capital"] == 500.0
        assert state["current_step"] == "START"
        assert state["completed_steps"] == []

    def test_workflow_nodes_exist(self):
        """Test all workflow nodes are importable."""
        from openclaw.workflow.nodes import (
            market_analysis_node,
            sentiment_analysis_node,
            fundamental_analysis_node,
            bull_bear_debate_node,
            decision_fusion_node,
            risk_assessment_node,
        )
        assert callable(market_analysis_node)
        assert callable(sentiment_analysis_node)
        assert callable(fundamental_analysis_node)
        assert callable(bull_bear_debate_node)
        assert callable(decision_fusion_node)
        assert callable(risk_assessment_node)


class TestWorkflowExecution:
    """Tests for workflow execution."""

    @pytest.mark.asyncio
    async def test_market_analysis_node(self):
        """Test market analysis node execution."""
        from openclaw.workflow.nodes import market_analysis_node
        from openclaw.workflow.state import create_initial_state

        state = create_initial_state(symbol="AAPL", initial_capital=1000.0)
        result = await market_analysis_node(state)

        assert "market_report" in result
        assert result["completed_steps"] == ["market_analysis"]

    @pytest.mark.asyncio
    async def test_sentiment_analysis_node(self):
        """Test sentiment analysis node execution."""
        from openclaw.workflow.nodes import sentiment_analysis_node
        from openclaw.workflow.state import create_initial_state

        state = create_initial_state(symbol="AAPL", initial_capital=1000.0)
        result = await sentiment_analysis_node(state)

        assert "sentiment_report" in result
        assert "sentiment_analysis" in result["completed_steps"]

    @pytest.mark.asyncio
    async def test_fundamental_analysis_node(self):
        """Test fundamental analysis node execution."""
        from openclaw.workflow.nodes import fundamental_analysis_node
        from openclaw.workflow.state import create_initial_state

        state = create_initial_state(symbol="AAPL", initial_capital=1000.0)
        result = await fundamental_analysis_node(state)

        assert "fundamental_report" in result
        assert "fundamental_analysis" in result["completed_steps"]


class TestWorkflowStateManagement:
    """Tests for workflow state management."""

    def test_state_reducer_for_completed_steps(self):
        """Test that completed steps are accumulated."""
        from openclaw.workflow.state import TradingWorkflowState

        state1: TradingWorkflowState = {
            "symbol": "AAPL",
            "initial_capital": 1000.0,
            "current_step": "market_analysis",
            "completed_steps": ["START"],
            "market_report": None,
            "sentiment_report": None,
            "fundamental_report": None,
            "bull_case": None,
            "bear_case": None,
            "fusion_result": None,
            "risk_assessment": None,
            "final_decision": None,
            "errors": [],
        }

        # Simulate adding a completed step
        state1["completed_steps"] = state1["completed_steps"] + ["market_analysis"]
        assert "market_analysis" in state1["completed_steps"]
        assert "START" in state1["completed_steps"]

    def test_state_error_handling(self):
        """Test that errors are tracked in state."""
        from openclaw.workflow.state import create_initial_state

        state = create_initial_state(symbol="AAPL", initial_capital=1000.0)
        assert state["errors"] == []

        # Simulate adding an error
        state["errors"] = state["errors"] + ["Test error"]
        assert "Test error" in state["errors"]
