"""Tests para enrich_org_passive.

Las funciones compuestas (whois_lookup, dns_records, enum_subdomains_crtsh) se
monkeypatchean para no tocar la red. Solo se verifica la orquestacion: que
ensambla las tres fuentes bajo las claves correctas y normaliza el dominio.
"""

import importlib
import os
import sys

import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from cybersecurity import enrich_org_passive

# El paquete re-exporta la funcion bajo el mismo nombre que el submodulo; para
# parchear los globals del modulo lo tomamos via importlib.
mod = importlib.import_module("cybersecurity.enrich_org_passive")


def test_golden_compone_whois_dns_subdomains(monkeypatch):
    monkeypatch.setattr(mod, "whois_lookup", lambda d: {"domain": d, "registrar": "OVH"})
    monkeypatch.setattr(mod, "dns_records", lambda d: {"A": ["1.2.3.4"], "MX": ["mx.x"]})
    monkeypatch.setattr(mod, "enum_subdomains_crtsh", lambda d: [f"www.{d}", f"api.{d}"])

    res = enrich_org_passive("organic-machine.com")

    assert res["whois"] == {"domain": "organic-machine.com", "registrar": "OVH"}
    assert res["dns"] == {"A": ["1.2.3.4"], "MX": ["mx.x"]}
    assert res["subdomains"] == ["www.organic-machine.com", "api.organic-machine.com"]
    assert set(res.keys()) == {"whois", "dns", "subdomains", "errors"}
    assert res["errors"] == {}  # sin fallos cuando todas las fuentes responden


def test_fuente_que_falla_se_captura_en_errors(monkeypatch):
    """Si una fuente externa peta (p.ej. crt.sh), se registra en errors y el resto se devuelve."""
    monkeypatch.setattr(mod, "whois_lookup", lambda d: {"registrar": "OVH"})
    monkeypatch.setattr(mod, "dns_records", lambda d: {"A": ["1.2.3.4"]})

    def boom(d):
        raise RuntimeError("crt.sh 404")
    monkeypatch.setattr(mod, "enum_subdomains_crtsh", boom)

    res = enrich_org_passive("organic-machine.com")
    assert res["whois"] == {"registrar": "OVH"}
    assert res["dns"] == {"A": ["1.2.3.4"]}
    assert res["subdomains"] == []
    assert "subdomains" in res["errors"] and "crt.sh 404" in res["errors"]["subdomains"]


def test_dominio_vacio_lanza(monkeypatch):
    monkeypatch.setattr(mod, "whois_lookup", lambda d: {})
    monkeypatch.setattr(mod, "dns_records", lambda d: {})
    monkeypatch.setattr(mod, "enum_subdomains_crtsh", lambda d: [])
    with pytest.raises(ValueError):
        enrich_org_passive("   ")


def test_dominio_con_espacios_se_normaliza(monkeypatch):
    seen = {}

    def whois(d):
        seen["whois"] = d
        return {}

    def dns(d):
        seen["dns"] = d
        return {}

    def subs(d):
        seen["subs"] = d
        return []

    monkeypatch.setattr(mod, "whois_lookup", whois)
    monkeypatch.setattr(mod, "dns_records", dns)
    monkeypatch.setattr(mod, "enum_subdomains_crtsh", subs)

    enrich_org_passive("  organic-machine.com  ")

    # Las tres funciones reciben el dominio ya sin espacios.
    assert seen == {
        "whois": "organic-machine.com",
        "dns": "organic-machine.com",
        "subs": "organic-machine.com",
    }
