"""Tests for the content analyzer (task tier classification)."""

import pytest

from proxym.providers import Capability, TaskTier
from proxym.router import analyze_request


class TestTierClassification:
    """Verify correct tier assignment for different prompt types."""

    def _msgs(self, text: str) -> list[dict]:
        return [{"role": "user", "content": text}]

    # ── Trivial tasks ────────────────────────────────────────

    def test_simple_question_is_trivial_or_operational(self):
        result = analyze_request(self._msgs("What is a Python list?"))
        assert result.tier in (TaskTier.TRIVIAL, TaskTier.OPERATIONAL)

    def test_show_command_is_trivial(self):
        result = analyze_request(self._msgs("Show me the file contents"))
        assert result.tier in (TaskTier.TRIVIAL, TaskTier.OPERATIONAL)

    def test_rename_is_trivial(self):
        result = analyze_request(self._msgs("Rename this variable from x to count"))
        assert result.tier in (TaskTier.TRIVIAL, TaskTier.OPERATIONAL)

    def test_fix_typo_is_trivial(self):
        result = analyze_request(self._msgs("Fix the typo in line 3"))
        # "Fix" matches standard pattern but "typo" signals trivial — router picks lowest
        assert result.tier in (TaskTier.TRIVIAL, TaskTier.OPERATIONAL, TaskTier.STANDARD)

    # ── Standard tasks ───────────────────────────────────────

    def test_implement_function_is_standard(self):
        result = analyze_request(self._msgs("Implement a function to parse CSV files"))
        assert result.tier in (TaskTier.STANDARD, TaskTier.OPERATIONAL)

    def test_write_tests_is_standard(self):
        result = analyze_request(self._msgs(
            "Write unit tests for the authentication module"
        ))
        assert result.tier in (TaskTier.STANDARD, TaskTier.OPERATIONAL)

    def test_fix_bug_is_standard(self):
        result = analyze_request(self._msgs(
            "Fix the bug where users can't login with special characters"
        ))
        assert result.tier in (TaskTier.STANDARD, TaskTier.OPERATIONAL)

    def test_code_review_is_standard(self):
        result = analyze_request(self._msgs("Code review this pull request"))
        assert result.tier in (TaskTier.STANDARD, TaskTier.OPERATIONAL)

    # ── Complex tasks ────────────────────────────────────────

    def test_refactor_entire_module_is_complex(self):
        result = analyze_request(self._msgs(
            "Refactor the entire authentication module to use the repository pattern"
        ))
        assert result.tier in (TaskTier.COMPLEX, TaskTier.DEEP_REASONING)

    def test_multi_file_change_is_complex(self):
        result = analyze_request(self._msgs(
            "Multi-file refactor: move all database logic from services to repositories"
        ))
        assert result.tier in (TaskTier.COMPLEX, TaskTier.DEEP_REASONING)

    def test_architecture_design_is_complex(self):
        result = analyze_request(self._msgs(
            "Design a system architecture for a real-time notification service"
        ))
        assert result.tier in (TaskTier.COMPLEX, TaskTier.DEEP_REASONING)

    def test_migration_is_complex(self):
        result = analyze_request(self._msgs(
            "Migrate from SQLAlchemy to Prisma across the entire project"
        ))
        assert result.tier in (TaskTier.COMPLEX, TaskTier.DEEP_REASONING)

    def test_security_audit_is_complex(self):
        result = analyze_request(self._msgs(
            "Security audit the API endpoints for vulnerability"
        ))
        assert result.tier in (TaskTier.COMPLEX, TaskTier.DEEP_REASONING)

    # ── Deep reasoning tasks ─────────────────────────────────

    def test_thinking_keyword_triggers_deep(self):
        result = analyze_request(self._msgs(
            "Think step by step about why this race condition occurs in the connection pool"
        ))
        assert result.tier == TaskTier.DEEP_REASONING
        assert Capability.THINKING in result.capabilities

    def test_root_cause_analysis_is_deep(self):
        result = analyze_request(self._msgs(
            "What causes this intermittent deadlock? Analyze the root cause carefully."
        ))
        assert Capability.THINKING in result.capabilities

    def test_tradeoffs_triggers_thinking(self):
        result = analyze_request(self._msgs(
            "Compare different approaches and evaluate trade-offs between event sourcing and CQRS"
        ))
        assert Capability.THINKING in result.capabilities


class TestCapabilityDetection:
    """Verify capability flags are correctly set."""

    def _msgs(self, text: str) -> list[dict]:
        return [{"role": "user", "content": text}]

    def test_vision_from_keyword(self):
        result = analyze_request(self._msgs("Analyze this screenshot of the error"))
        assert Capability.VISION in result.capabilities

    def test_vision_from_image_block(self):
        msgs = [{
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}},
                {"type": "text", "text": "What's in this image?"},
            ],
        }]
        result = analyze_request(msgs)
        assert Capability.VISION in result.capabilities

    def test_code_capability_from_keywords(self):
        result = analyze_request(self._msgs("Implement a new API endpoint"))
        assert Capability.CODE in result.capabilities

    def test_tool_use_detection(self):
        result = analyze_request(self._msgs("Use the function call to query the database"))
        assert Capability.TOOL_USE in result.capabilities

    def test_long_context_from_tokens(self):
        result = analyze_request(
            self._msgs("Analyze the codebase"),
            context_tokens=150_000,
        )
        assert Capability.LONG_CONTEXT in result.capabilities

    def test_multi_file_raises_tier(self):
        result = analyze_request(
            self._msgs("Update the module"),
            file_count=8,
        )
        assert result.tier in (TaskTier.STANDARD, TaskTier.COMPLEX)


class TestExplicitOverrides:
    """Verify explicit tier and model overrides."""

    def _msgs(self, text: str) -> list[dict]:
        return [{"role": "user", "content": text}]

    def test_explicit_tier_header(self):
        result = analyze_request(self._msgs("hello"), explicit_tier="complex")
        assert result.tier == TaskTier.COMPLEX
        assert result.confidence == 1.0

    def test_explicit_tier_invalid_falls_to_standard(self):
        result = analyze_request(self._msgs("hello"), explicit_tier="nonexistent")
        assert result.tier == TaskTier.STANDARD

    def test_explicit_model_passthrough(self):
        result = analyze_request(
            self._msgs("hello"),
            explicit_model="anthropic/opus-4.6",
        )
        assert result.confidence == 1.0
        assert "Explicit model" in result.reasoning
