"""
SDK Package Tests

Verify that individual SDK packages (cxr-k1, cxr-k2, etc.) can be imported
and used correctly.
"""

import pytest
import sys
from pathlib import Path


# Add SDK package paths to sys.path for testing
SDK_BASE = Path(__file__).resolve().parents[2] / "sdk-models"


def test_cxr_k1_import():
    """Test cxr_k1 package can be imported"""
    # Add package path
    k1_path = SDK_BASE / "cxr-k1"
    if str(k1_path) not in sys.path:
        sys.path.insert(0, str(k1_path))
    
    try:
        import cxr_k1
        assert hasattr(cxr_k1, "get_model")
        assert hasattr(cxr_k1, "analyze")
        assert hasattr(cxr_k1, "__version__")
    except ImportError:
        pytest.skip("cxr_k1 package not available (may need to install)")


def test_cxr_k1_get_model():
    """Test cxr_k1.get_model() returns k1 instance"""
    k1_path = SDK_BASE / "cxr-k1"
    if str(k1_path) not in sys.path:
        sys.path.insert(0, str(k1_path))
    
    try:
        from cxr_k1 import get_model
        model = get_model()
        assert model is not None
        assert model.model_id == "cxr-k1"
    except ImportError:
        pytest.skip("cxr_k1 package not available")


def test_cxr_k1_analyze():
    """Test cxr_k1.analyze() function works"""
    k1_path = SDK_BASE / "cxr-k1"
    if str(k1_path) not in sys.path:
        sys.path.insert(0, str(k1_path))
    
    try:
        from cxr_k1 import analyze, get_model
        from unittest.mock import Mock
        
        claim = {
            "claimId": "TEST-001",
            "patientId": "PAT-001",
            "billedAmount": 100.0,
            "metadata": {"reviewThreshold": 0.8}
        }
        
        # Mock the model's dependencies properly
        mock_fusion = Mock()
        mock_fusion.get_structured_evidence = Mock(return_value=0.7)
        mock_fusion.get_unstructured_evidence = Mock(return_value=0.6)
        mock_fusion.get_contextual_evidence = Mock(return_value=0.5)
        mock_fusion.get_patient_evidence = Mock(return_value=0.4)
        mock_fusion.get_provider_evidence = Mock(return_value=0.3)
        mock_fusion.get_payer_evidence = Mock(return_value=0.2)
        mock_fusion.get_temporal_evidence = Mock(return_value=0.1)
        mock_fusion.fuse = Mock(return_value=(0.6, {}))
        
        mock_context = Mock()
        mock_context.get_patient_context = Mock(return_value={"patient_denial_rate": 0.2})
        mock_context.get_provider_context = Mock(return_value={"provider_denial_rate": 0.15})
        mock_context.get_payer_context = Mock(return_value={"payer_denial_rate": 0.25})
        mock_context.get_temporal_context = Mock(return_value={"claim_age_days": 30})
        mock_context.get_financial_context = Mock(return_value={})
        mock_context.get_relationship_context = Mock(return_value={})
        mock_context.get_policy_context = Mock(return_value={})
        
        model = get_model()
        model._fusion_engine = mock_fusion
        model._context_collector = mock_context
        
        result = analyze(claim, tenant_id="test-tenant")
        assert isinstance(result, dict)
        assert "verdict" in result
    except ImportError:
        pytest.skip("cxr_k1 package not available")


def test_cxr_k2_import():
    """Test cxr_k2 package can be imported"""
    k2_path = SDK_BASE / "cxr-k2"
    if str(k2_path) not in sys.path:
        sys.path.insert(0, str(k2_path))
    
    try:
        import cxr_k2
        assert hasattr(cxr_k2, "get_model")
        assert hasattr(cxr_k2, "analyze")
    except ImportError:
        pytest.skip("cxr_k2 package not available")


def test_cxr_k_sim1_import():
    """Test cxr_k_sim1 package can be imported"""
    sim1_path = SDK_BASE / "cxr-k-sim1"
    if str(sim1_path) not in sys.path:
        sys.path.insert(0, str(sim1_path))
    
    try:
        import cxr_k_sim1
        assert hasattr(cxr_k_sim1, "get_model")
        assert hasattr(cxr_k_sim1, "analyze")
    except ImportError:
        pytest.skip("cxr_k_sim1 package not available")


def test_cxr_k_lite1_import():
    """Test cxr_k_lite1 package can be imported"""
    lite1_path = SDK_BASE / "cxr-k-lite1"
    if str(lite1_path) not in sys.path:
        sys.path.insert(0, str(lite1_path))
    
    try:
        import cxr_k_lite1
        assert hasattr(cxr_k_lite1, "get_model")
        assert hasattr(cxr_k_lite1, "analyze")
    except ImportError:
        pytest.skip("cxr_k_lite1 package not available")


def test_cxr_k_audit1_import():
    """Test cxr_k_audit1 package can be imported"""
    audit1_path = SDK_BASE / "cxr-k-audit1"
    if str(audit1_path) not in sys.path:
        sys.path.insert(0, str(audit1_path))
    
    try:
        import cxr_k_audit1
        assert hasattr(cxr_k_audit1, "get_model")
        assert hasattr(cxr_k_audit1, "analyze")
    except ImportError:
        pytest.skip("cxr_k_audit1 package not available")


def test_package_versions():
    """Test packages have version attributes"""
    packages = [
        ("cxr-k1", "cxr_k1"),
        ("cxr-k2", "cxr_k2"),
        ("cxr-k-sim1", "cxr_k_sim1"),
        ("cxr-k-lite1", "cxr_k_lite1"),
        ("cxr-k-audit1", "cxr_k_audit1"),
    ]
    
    for pkg_dir, pkg_name in packages:
        pkg_path = SDK_BASE / pkg_dir
        if str(pkg_path) not in sys.path:
            sys.path.insert(0, str(pkg_path))
        
        try:
            module = __import__(pkg_name)
            if hasattr(module, "__version__"):
                version = module.__version__
                assert isinstance(version, str)
                assert len(version) > 0
        except ImportError:
            pytest.skip(f"{pkg_name} package not available")


def test_package_dependencies():
    """Test packages declare correct dependencies"""
    # This would check pyproject.toml files
    # For now, just verify packages can import kernel_service
    packages = [
        ("cxr-k1", "cxr_k1"),
        ("cxr-k2", "cxr_k2"),
        ("cxr-k-sim1", "cxr_k_sim1"),
        ("cxr-k-lite1", "cxr_k_lite1"),
        ("cxr-k-audit1", "cxr_k_audit1"),
    ]
    
    for pkg_dir, pkg_name in packages:
        pkg_path = SDK_BASE / pkg_dir
        if str(pkg_path) not in sys.path:
            sys.path.insert(0, str(pkg_path))
        
        try:
            module = __import__(pkg_name)
            # Verify it can access kernel_service (the dependency)
            from kernel_service.registry import get_registry
            assert get_registry() is not None
        except ImportError:
            pytest.skip(f"{pkg_name} package or kernel_service not available")

