from __future__ import annotations

from pathlib import Path
import sys
from types import SimpleNamespace

from cf_ontology.package_discovery import _load_documents_from_descriptor, discover_step_packages


def _repo_root() -> Path:
    return Path(__file__).resolve().parents[3]


def _add_step_package_source(package_name: str) -> None:
    src_root = _repo_root() / "sandcastle" / "cf_basic_steps" / package_name / "src"
    if str(src_root) not in sys.path:
        sys.path.insert(0, str(src_root))


def test_discover_step_packages_accepts_steps_nq_entry_points(monkeypatch) -> None:
    _add_step_package_source("cf_basic_signal")

    entry_point = SimpleNamespace(
        name="cf.basic.signal",
        value="cf_basic_signal:steps.nq",
        dist=SimpleNamespace(name="cf-basic-signal", version="0.2.4"),
    )
    monkeypatch.setattr(
        "cf_ontology.package_discovery._iter_step_entry_points",
        lambda: [entry_point],
    )

    descriptors = discover_step_packages()
    assert len(descriptors) == 1

    descriptor = descriptors[0]
    assert descriptor.document_paths == ["steps.nq"]

    documents = _load_documents_from_descriptor(descriptor)
    assert len(documents) == 1

    document, _, source_path = documents[0]
    assert str(source_path).endswith("steps.nq")

    graph_nodes = document.get("@graph")
    assert isinstance(graph_nodes, list)
    package_node = next(
        node
        for node in graph_nodes
        if isinstance(node, dict) and str(node.get("@id", "")).endswith("basic-signal/BasicSignalPackage")
    )
    assert package_node.get("cf:packageId") == "cf.basic.signal"
