from types import SimpleNamespace

import pytest

from kernel_service.fusion.seven_plane import SevenPlaneFusionEngine


def test_fuse_normalizes_weights(sample_claim, mock_db_conn, mock_qdrant_client):
    engine = SevenPlaneFusionEngine(db_conn=mock_db_conn, qdrant_client=mock_qdrant_client)
    evidence = {plane: 0.8 for plane in engine.default_weights.keys()}

    fused, contributions = engine.fuse(evidence)

    assert 0.0 <= fused <= 1.0
    assert len(contributions) == 7
    assert pytest.approx(sum(c["contribution"] for c in contributions.values()), rel=1e-6) == fused


def test_structured_evidence_uses_db(mock_db_conn):
    engine = SevenPlaneFusionEngine(db_conn=mock_db_conn)
    score = engine.get_structured_evidence({}, "DEFAULT")
    assert score == pytest.approx(0.85)


def test_structured_evidence_without_db_defaults():
    engine = SevenPlaneFusionEngine(db_conn=None)
    score = engine.get_structured_evidence({}, "DEFAULT")
    assert score == pytest.approx(0.5)


def test_unstructured_evidence_without_qdrant_defaults():
    engine = SevenPlaneFusionEngine(db_conn=None, qdrant_client=None)
    score = engine.get_unstructured_evidence({}, {})
    assert score == pytest.approx(0.5)


def test_contextual_evidence_reflects_threshold(sample_claim):
    engine = SevenPlaneFusionEngine(db_conn=None)
    sample_claim["metadata"]["reviewThreshold"] = 0.9
    score = engine.get_contextual_evidence(sample_claim)
    assert score == pytest.approx(0.1)


def test_patient_evidence_handles_risk_flag():
    engine = SevenPlaneFusionEngine(db_conn=None)
    context = {"patient_denial_rate": 0.3, "patient_risk_flag": True}
    score = engine.get_patient_evidence(context)
    assert score == pytest.approx(0.5)


def test_provider_evidence_adjusts_for_risk_level():
    engine = SevenPlaneFusionEngine(db_conn=None)
    context = {"provider_denial_rate": 0.25, "provider_risk_level": "HIGH"}
    score = engine.get_provider_evidence(context)
    assert score == pytest.approx(0.4)


def test_payer_evidence_accounts_for_strictness():
    engine = SevenPlaneFusionEngine(db_conn=None)
    context = {"payer_denial_rate": 0.4, "payer_strictness": "HIGH"}
    score = engine.get_payer_evidence(context)
    assert score == pytest.approx(0.5)


def test_temporal_evidence_incorporates_age():
    engine = SevenPlaneFusionEngine(db_conn=None)
    context = {"claim_age_days": 180, "is_urgent": False}
    score = engine.get_temporal_evidence(context)
    assert 0.5 < score < 0.7

