"""Tests for wiki/rdf/vocabulary.py -- YAML concept loading."""

from __future__ import annotations

import textwrap
from pathlib import Path

import pytest

from pycharter.wiki.rdf.context import DEFAULT_BASE_URI, set_base_uri
from pycharter.wiki.rdf.vocabulary import load_vocabulary
from pycharter.wiki.shared.errors import OntologyError


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

    def test_load_yaml(self, tmp_path: Path):
        f = tmp_path / "ontologies.yaml"
        f.write_text(textwrap.dedent("""\
            scheme:
              id: Test
              title: Test Scheme
              version: "1.0.0"
            concepts:
              - id: Alpha
                label: Alpha
                definition: First
              - id: Beta
                label: Beta
                broader: Alpha
                tags: [t1]
            """))
        scheme = load_vocabulary(str(f))
        assert scheme.id == "Test"
        assert len(scheme.concepts) == 2
        assert scheme.concepts[1].broader == "Alpha"
        assert scheme.concepts[1].tags == ["t1"]

    def test_load_yaml_with_new_keys(self, tmp_path: Path):
        f = tmp_path / "ontologies.yaml"
        f.write_text(textwrap.dedent("""\
            scheme:
              id: Test
              title: Test
              version: "1.0.0"
              base_uri: https://custom.org/ont/
            concepts:
              - id: Foo
                label: Foo
                alt_labels: [F]
                notation: FOO
                examples: ["ex1"]
                exact_match: https://example.com/foo
                deprecated: true
                replaced_by: Bar
            """))
        scheme = load_vocabulary(str(f))
        c = scheme.concepts[0]
        assert c.alt_labels == ["F"]
        assert c.notation == "FOO"
        assert c.examples == ["ex1"]
        assert c.exact_match == "https://example.com/foo"
        assert c.deprecated is True
        assert c.replaced_by == "Bar"

    def test_missing_file(self, tmp_path: Path):
        with pytest.raises(OntologyError, match="not found"):
            load_vocabulary(str(tmp_path / "missing.yaml"))

    def test_unsupported_format(self, tmp_path: Path):
        f = tmp_path / "concepts.txt"
        f.write_text("hello")
        with pytest.raises(OntologyError, match="Unsupported"):
            load_vocabulary(str(f))

    def test_load_existing_seed_file(self):
        """Ensure the actual seed ontologies.yaml loads without error."""
        seed = (
            Path(__file__).resolve().parent.parent.parent.parent
            / "src"
            / "pycharter"
            / "data"
            / "seed"
            / "ontologies.yaml"
        )
        if not seed.exists():
            pytest.skip("seed ontologies.yaml not found")
        scheme = load_vocabulary(str(seed))
        assert len(scheme.concepts) > 0
        assert scheme.id == "StatFYITradingDomain"
