"""Round-trip tests: YAML -> internal -> JSON-LD -> internal (and back)."""

from __future__ import annotations

from pycharter.wiki.ontology.models import (
    ConceptDefinition,
    ConceptScheme,
    FieldOntology,
    Lineage,
    OntologyArtifact,
    Relationship,
    RelationshipType,
)
from pycharter.wiki.rdf.context import DEFAULT_BASE_URI, set_base_uri
from pycharter.wiki.rdf.emitter import emit_concepts_jsonld, emit_ontology_jsonld
from pycharter.wiki.rdf.jsonld_parser import (
    parse_concepts_jsonld,
    parse_ontology_jsonld,
)


class TestConceptRoundTrip:
    def setup_method(self):
        set_base_uri(DEFAULT_BASE_URI)

    def test_emit_then_parse(self):
        original = ConceptScheme(
            id="RT",
            title="Round Trip",
            version="2.0.0",
            concepts=[
                ConceptDefinition(
                    id="Alpha",
                    label="Alpha",
                    definition="First concept",
                    tags=["tag1"],
                ),
                ConceptDefinition(
                    id="Beta",
                    label="Beta",
                    broader="Alpha",
                    alt_labels=["B"],
                    notation="BETA",
                ),
            ],
        )

        doc = emit_concepts_jsonld(original)
        parsed = parse_concepts_jsonld(doc)

        assert parsed.title == original.title
        assert parsed.version == original.version
        assert len(parsed.concepts) == len(original.concepts)

        by_id = {c.id: c for c in parsed.concepts}
        assert by_id["Alpha"].label == "Alpha"
        assert by_id["Alpha"].definition == "First concept"
        assert by_id["Beta"].broader == "Alpha"


class TestOntologyRoundTrip:
    def setup_method(self):
        set_base_uri(DEFAULT_BASE_URI)

    def test_emit_then_parse(self):
        original = OntologyArtifact(
            version="1.0.0",
            fields={
                "order_id": FieldOntology(
                    concept="OrderIdentifier",
                    tags=["pk"],
                    owner="eng",
                    description="The order ID",
                ),
                "amount": FieldOntology(
                    concept="MonetaryAmount",
                    lineage=Lineage(derived_from="raw_amount", source_system="billing"),
                ),
            },
        )

        doc = emit_ontology_jsonld(original, "order_domain")
        parsed = parse_ontology_jsonld(doc)

        assert parsed.version == original.version
        assert set(parsed.fields.keys()) == set(original.fields.keys())

        oid = parsed.fields["order_id"]
        assert oid.concept == "OrderIdentifier"
        assert oid.tags == ["pk"]
        assert oid.owner == "eng"
        assert oid.description == "The order ID"
