"""
Work Assistant Agent 테스트
"""

import pytest
import asyncio
import os
import sys

# 상위 디렉토리 추가
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from work_assistant_agent import WorkAssistantAgent, AgentConfig, AgentContext
from work_assistant_agent.mcp_client import MCPClientManager, MCPServerConfig


class TestAgentConfig:
    """AgentConfig 테스트"""
    
    def test_default_config(self):
        """기본 설정 테스트"""
        config = AgentConfig()
        assert config.model_provider == "openai"
        assert config.model_name == "gpt-4o"
        assert config.temperature == 0.0
        assert config.streaming == True
    
    def test_custom_config(self):
        """커스텀 설정 테스트"""
        config = AgentConfig(
            model_provider="anthropic",
            model_name="claude-3-5-sonnet-20241022",
            temperature=0.5
        )
        assert config.model_provider == "anthropic"
        assert config.model_name == "claude-3-5-sonnet-20241022"
        assert config.temperature == 0.5


class TestAgentContext:
    """AgentContext 테스트"""
    
    def test_default_context(self):
        """기본 컨텍스트 테스트"""
        context = AgentContext()
        assert context.tenant_id == ""
        assert context.conversation_history == []
    
    def test_custom_context(self):
        """커스텀 컨텍스트 테스트"""
        context = AgentContext(
            tenant_id="uengine",
            user_uid="test-uid",
            user_email="test@example.com"
        )
        assert context.tenant_id == "uengine"
        assert context.user_uid == "test-uid"


class TestMCPClientManager:
    """MCPClientManager 테스트"""
    
    def test_register_server(self):
        """서버 등록 테스트"""
        client = MCPClientManager()
        client.register_server(
            name="test-server",
            command="python",
            args=["-m", "test_server"],
            env={"TEST": "value"}
        )
        
        assert "test-server" in client.servers
        assert client.servers["test-server"].command == "python"
        assert client.servers["test-server"].args == ["-m", "test_server"]
        assert client.servers["test-server"].env == {"TEST": "value"}
    
    def test_load_config_from_dict(self):
        """설정 로드 테스트 (딕셔너리에서)"""
        client = MCPClientManager()
        
        # 서버 직접 등록
        client.register_server(
            name="work-assistant",
            command="uvx",
            args=["work-assistant-mcp"],
            enabled=True
        )
        
        assert "work-assistant" in client.servers
        assert client.servers["work-assistant"].enabled == True


class TestWorkAssistantAgent:
    """WorkAssistantAgent 테스트"""
    
    def test_agent_creation(self):
        """에이전트 생성 테스트"""
        config = AgentConfig(
            model_provider="openai",
            model_name="gpt-4o"
        )
        agent = WorkAssistantAgent(config)
        
        assert agent.config == config
        assert agent._initialized == False
    
    @pytest.mark.asyncio
    async def test_agent_initialization_without_mcp(self):
        """MCP 없이 에이전트 초기화 테스트"""
        config = AgentConfig(
            model_provider="openai",
            model_name="gpt-4o"
        )
        agent = WorkAssistantAgent(config)
        
        # API 키가 없으면 실패할 수 있음
        if os.getenv("OPENAI_API_KEY"):
            await agent.initialize()
            assert agent._initialized == True
            assert agent.llm is not None
            await agent.cleanup()
    
    def test_prepare_messages(self):
        """메시지 준비 테스트"""
        config = AgentConfig()
        agent = WorkAssistantAgent(config)
        
        context = AgentContext(
            tenant_id="uengine",
            user_uid="test-uid",
            user_email="test@example.com",
            user_name="테스터"
        )
        
        messages = agent._prepare_messages("안녕하세요", context)
        
        # 시스템 메시지 + 사용자 메시지
        assert len(messages) >= 2
        assert "tenant_id: uengine" in messages[0].content
        assert messages[-1].content == "안녕하세요"


# 통합 테스트 (실제 API 호출 필요)
@pytest.mark.skipif(
    not os.getenv("OPENAI_API_KEY"),
    reason="OPENAI_API_KEY가 설정되지 않음"
)
class TestAgentIntegration:
    """통합 테스트"""
    
    @pytest.mark.asyncio
    async def test_simple_conversation(self):
        """간단한 대화 테스트"""
        config = AgentConfig(
            model_provider="openai",
            model_name="gpt-4o"
        )
        agent = WorkAssistantAgent(config)
        
        try:
            await agent.initialize()
            
            context = AgentContext(
                tenant_id="test",
                user_email="test@example.com"
            )
            
            response = await agent.run("안녕하세요", context, stream=False)
            
            assert response is not None
            assert len(response) > 0
            
        finally:
            await agent.cleanup()


if __name__ == "__main__":
    pytest.main([__file__, "-v"])

