"""Tests for XAI Suite IA client."""

import pytest
from unittest.mock import AsyncMock, patch, MagicMock

from xai_suite.ia import IAClient
from xai_suite.ia.models import (
    ExplanationRequest,
    ExplanationRequestV2,
    NarrativeResponse,
    ExplanationResponseV2,
    Insight,
)


class TestIAClientInitialization:
    """Tests for IAClient initialization."""

    def test_basic_initialization(self):
        """Test basic client initialization."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key"
        )

        assert client.endpoint == "http://localhost:8000"
        assert client.api_key == "test-key"

    def test_initialization_with_domain(self):
        """Test initialization with domain."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key",
            domain="cybersecurity"
        )

        assert client.domain == "cybersecurity"

    def test_default_domain(self):
        """Test default domain is generic."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key"
        )

        assert client.domain == "generic"

    def test_endpoint_trailing_slash_removed(self):
        """Test trailing slash is removed from endpoint."""
        client = IAClient(
            endpoint="http://localhost:8000/",
            api_key="test-key"
        )

        assert client.endpoint == "http://localhost:8000"


class TestIAClientProperties:
    """Tests for IAClient properties."""

    def test_set_domain(self):
        """Test setting domain."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key"
        )

        client.domain = "cybersecurity"
        assert client.domain == "cybersecurity"

    def test_api_key_stored(self):
        """Test that API key is stored."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key"
        )

        assert client.api_key == "test-key"


class TestIAClientRequestBuilding:
    """Tests for building requests."""

    def test_build_v2_request_model(self, sample_shap_explanation):
        """Test building V2 request model directly."""
        request = ExplanationRequestV2(
            method=sample_shap_explanation["method"],
            feature_names=sample_shap_explanation["feature_names"],
            importance_scores=sample_shap_explanation["importance_scores"],
            feature_values=sample_shap_explanation.get("feature_values"),
            base_value=sample_shap_explanation.get("base_value"),
            output_value=sample_shap_explanation.get("output_value"),
            model_type="anomaly_detection",
            domain="cybersecurity",
            include_insights=True,
            include_compliance=True
        )

        assert isinstance(request, ExplanationRequestV2)
        assert request.method == "SHAP"
        assert request.domain == "cybersecurity"
        assert request.include_insights is True
        assert request.include_compliance is True

    def test_build_v2_request_with_context(self, sample_shap_explanation):
        """Test building V2 request with context."""
        request = ExplanationRequestV2(
            method=sample_shap_explanation["method"],
            feature_names=sample_shap_explanation["feature_names"],
            importance_scores=sample_shap_explanation["importance_scores"],
            model_type="anomaly_detection",
            domain="cybersecurity",
            domain_context={"network_segment": "dmz"}
        )

        assert request.domain_context == {"network_segment": "dmz"}


class TestIAClientSync:
    """Tests for synchronous client methods."""

    def test_health_check_url(self):
        """Test health check URL construction."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key"
        )

        url = f"{client.endpoint}/api/v1/health"
        assert url == "http://localhost:8000/api/v1/health"

    def test_domains_url(self):
        """Test domains URL construction."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key"
        )

        url = f"{client.endpoint}/api/v1/domains"
        assert url == "http://localhost:8000/api/v1/domains"

    def test_explain_url(self):
        """Test explain URL construction."""
        client = IAClient(
            endpoint="http://localhost:8000",
            api_key="test-key"
        )

        url = f"{client.endpoint}/api/v1/v2/explain"
        assert url == "http://localhost:8000/api/v1/v2/explain"


class TestIAClientExplanationParsing:
    """Tests for parsing explanation responses."""

    def test_parse_insight(self):
        """Test parsing insight from response."""
        insight_data = {
            "type": "warning",
            "priority": "high",
            "title": "Test Insight",
            "description": "Test description",
            "action": "Take action",
            "related_features": ["feature_1"]
        }

        insight = Insight(**insight_data)

        assert insight.type == "warning"
        assert insight.priority == "high"
        assert insight.title == "Test Insight"
        assert insight.action == "Take action"
        assert "feature_1" in insight.related_features

    def test_insight_optional_action(self):
        """Test that insight action is optional."""
        insight_data = {
            "type": "observation",
            "priority": "low",
            "title": "Test Observation",
            "description": "Test description",
            "related_features": []
        }

        insight = Insight(**insight_data)
        assert insight.action is None
