"""Routeline policy-gate tests."""

from __future__ import annotations

from psyc.lines.route import plan
from psyc.models import IncidentType, Severity, TLP
from conftest import make_case


def _dest_names(routes):
    return {r.destination_name for r in routes}


def _blocked_reasons(blocked):
    return {b.destination_name: b.reason for b in blocked}


def test_green_malware_routes_to_misp_and_urlhaus():
    case = make_case(incident_type=IncidentType.MALWARE, severity=Severity.HIGH, tlp=TLP.GREEN)
    routes, blocked = plan(case)
    assert {"MISP-Community", "URLhaus"} <= _dest_names(routes)


def test_tlp_ceiling_blocks_abuseipdb():
    # AbuseIPDB max TLP is CLEAR; a GREEN case must be blocked there
    case = make_case(incident_type=IncidentType.MALWARE, severity=Severity.HIGH, tlp=TLP.GREEN)
    _, blocked = plan(case)
    assert _blocked_reasons(blocked).get("AbuseIPDB") == "tlp_exceeded"


def test_country_gate_blocks_cert_bund_when_not_de():
    case = make_case(incident_type=IncidentType.MALWARE, severity=Severity.HIGH, tlp=TLP.AMBER, country="CN")
    _, blocked = plan(case)
    assert _blocked_reasons(blocked).get("CERT-Bund") == "country_mismatch"


def test_country_gate_allows_cert_bund_for_de():
    case = make_case(incident_type=IncidentType.MALWARE, severity=Severity.HIGH, tlp=TLP.AMBER, country="DE")
    routes, _ = plan(case)
    assert "CERT-Bund" in _dest_names(routes)


def test_incident_type_gate_blocks_urlhaus_for_non_malware():
    case = make_case(incident_type=IncidentType.BOTNET, severity=Severity.HIGH, tlp=TLP.GREEN)
    _, blocked = plan(case)
    assert _blocked_reasons(blocked).get("URLhaus") == "incident_type_mismatch"


def test_routes_sorted_by_priority():
    case = make_case(incident_type=IncidentType.MALWARE, severity=Severity.HIGH, tlp=TLP.GREEN, country="DE")
    routes, _ = plan(case)
    assert [r.priority for r in routes] == sorted(r.priority for r in routes)
