"""Tests for framework support functionality."""

import pytest
from src.agentman.agentfile_parser import AgentfileParser
from src.agentman.agent_builder import AgentBuilder
import tempfile
from pathlib import Path


class TestFrameworkSupport:
    """Test framework detection and code generation."""

    def test_framework_parsing_fast_agent_default(self):
        """Test that FastAgent is the default framework."""
        content = """
FROM yeahdongcn/agentman-base:latest
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)
        assert config.framework == "fast-agent"

    def test_framework_parsing_agno_explicit(self):
        """Test parsing explicit Agno framework."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)
        assert config.framework == "agno"

    def test_framework_parsing_fast_agent_explicit(self):
        """Test parsing explicit FastAgent framework."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK fast-agent
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)
        assert config.framework == "fast-agent"

    def test_framework_validation_invalid(self):
        """Test that invalid framework raises error."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK invalid-framework
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        with pytest.raises(ValueError, match="Unsupported framework"):
            parser.parse_content(content)

    def test_fast_agent_code_generation(self):
        """Test FastAgent code generation."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK fast-agent
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            code = builder._build_python_content()

            assert "from mcp_agent.core.fastagent import FastAgent" in code
            assert 'FastAgent("Generated by Agentman")' in code
            assert "@fast.agent" in code
            assert "async with fast.run() as agent:" in code

    def test_agno_code_generation(self):
        """Test Agno code generation."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            code = builder._build_python_content()

            assert "from agno.agent import Agent" in code
            assert "from agno.models.anthropic import Claude" in code
            assert "from agno.tools.reasoning import ReasoningTools" in code
            assert "Agent(" in code
            assert "Claude(id=" in code
            assert ".arun(" in code
            assert "show_full_reasoning=True" in code
            assert "stream_intermediate_steps=True" in code

    def test_agno_multi_agent_team_generation(self):
        """Test Agno multi-agent team generation."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-sonnet-20241022
AGENT researcher
INSTRUCTION Research specialist
SERVERS web_search
AGENT analyst
INSTRUCTION Data analyst
SERVERS finance
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            code = builder._build_python_content()

            # Check for team imports
            assert "from agno.team.team import Team" in code

            # Check for multiple agents
            assert "researcher_agent = Agent(" in code
            assert "analyst_agent = Agent(" in code

            # Check for team creation
            assert "agentteam = Team(" in code
            assert "members=[researcher_agent, analyst_agent]" in code
            assert "mode='coordinate'" in code
            assert "show_members_responses=True" in code
            assert "enable_agentic_context=True" in code

            # Check for enhanced tools
            assert "DuckDuckGoTools()" in code
            assert "YFinanceTools(stock_price=True, analyst_recommendations=True)" in code

    def test_fast_agent_requirements(self):
        """Test FastAgent requirements generation."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK fast-agent
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            requirements = builder._get_fast_agent_requirements()

            assert "fast-agent-mcp>=0.2.33" in requirements
            assert "deprecated>=1.2.18" in requirements

    def test_agno_requirements(self):
        """Test Agno requirements generation."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
SERVERS web_search finance
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            requirements = builder._get_agno_requirements()

            assert "agno>=1.6.0" in requirements
            assert "anthropic" in requirements
            assert "mcp" in requirements
            assert "duckduckgo-search" in requirements
            assert "yfinance" in requirements
            assert "sqlalchemy" in requirements
            assert "lancedb" in requirements
            assert "tantivy" in requirements

    def test_openai_model_requirements(self):
        """Test that OpenAI models add OpenAI dependency."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL openai/gpt-4
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            requirements = builder._get_agno_requirements()

            assert "openai" in requirements

    def test_fast_agent_config_generation(self):
        """Test FastAgent config file generation."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK fast-agent
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
SECRET ANTHROPIC_API_KEY
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            builder._generate_config_yaml()
            builder._generate_secrets_yaml()

            # Check that FastAgent config files are created
            assert (Path(temp_dir) / "fastagent.config.yaml").exists()
            assert (Path(temp_dir) / "fastagent.secrets.yaml").exists()
            assert not (Path(temp_dir) / ".env").exists()

    def test_agno_config_generation(self):
        """Test Agno config file generation."""
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
SECRET ANTHROPIC_API_KEY
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            builder._generate_config_yaml()
            builder._generate_secrets_yaml()

            # Check that Agno config files are created
            assert (Path(temp_dir) / ".env").exists()
            assert not (Path(temp_dir) / "fastagent.config.yaml").exists()
            assert not (Path(temp_dir) / "fastagent.secrets.yaml").exists()

    def test_dockerfile_framework_specific_copy(self):
        """Test that Dockerfile copies correct config files for each framework."""
        # Test FastAgent
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK fast-agent
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            builder._generate_dockerfile()

            with open(Path(temp_dir) / "Dockerfile", 'r') as f:
                dockerfile_content = f.read()
                assert "COPY fastagent.config.yaml ." in dockerfile_content
                assert "COPY fastagent.secrets.yaml ." in dockerfile_content
                assert "COPY .env ." not in dockerfile_content

        # Test Agno
        content = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        config = parser.parse_content(content)

        with tempfile.TemporaryDirectory() as temp_dir:
            builder = AgentBuilder(config, temp_dir)
            builder._generate_dockerfile()

            with open(Path(temp_dir) / "Dockerfile", 'r') as f:
                dockerfile_content = f.read()
                assert "COPY .env ." in dockerfile_content
                assert "COPY fastagent.config.yaml ." not in dockerfile_content
                assert "COPY fastagent.secrets.yaml ." not in dockerfile_content

    def test_build_output_messages(self):
        """Test that build completion shows correct files for each framework."""
        # This would need to be tested by capturing print output
        # For now, we'll just verify the logic exists
        content_agno = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        parser = AgentfileParser()
        config = parser.parse_content(content_agno)
        assert config.framework == "agno"

        content_fast = """
FROM yeahdongcn/agentman-base:latest
FRAMEWORK fast-agent
MODEL anthropic/claude-3-sonnet-20241022
AGENT test
INSTRUCTION Test agent
"""
        config = parser.parse_content(content_fast)
        assert config.framework == "fast-agent"

    def test_agent_specific_model_instruction(self):
        """Test that MODEL instruction within AGENT context works correctly."""
        agentfile_content = """FROM yeahdongcn/agentman-base:latest
FRAMEWORK agno
MODEL anthropic/claude-3-haiku-20240307

MCP_SERVER web_search
COMMAND uvx
ARGS mcp-server-duckduckgo
TRANSPORT stdio

AGENT research_agent
INSTRUCTION You are a research agent
SERVERS web_search
MODEL anthropic/claude-3-sonnet-20241022
USE_HISTORY true
HUMAN_INPUT false
"""

        parser = AgentfileParser()
        config = parser.parse_content(agentfile_content)

        # Check global model
        assert config.default_model == "anthropic/claude-3-haiku-20240307"

        # Check agent-specific model
        assert "research_agent" in config.agents
        agent = config.agents["research_agent"]
        assert agent.model == "anthropic/claude-3-sonnet-20241022"
        assert agent.use_history is True
        assert agent.human_input is False
        assert agent.servers == ["web_search"]
