"""
SHACL shapes manager -- load and list shape graphs from files.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

from pycharter.wiki.rdf import _check_rdflib

_DEFAULT_SHAPES_DIR: Path | None = None


def _get_default_shapes_dir() -> Path:
    """Return the built-in shapes directory shipped with pycharter."""
    global _DEFAULT_SHAPES_DIR
    if _DEFAULT_SHAPES_DIR is None:
        _DEFAULT_SHAPES_DIR = (
            Path(__file__).resolve().parent.parent.parent
            / "data"
            / "ontology"
            / "shapes"
        )
    return _DEFAULT_SHAPES_DIR


def load_shapes(path: str | Path) -> Any:
    """
    Load a single SHACL shapes file into an ``rdflib.Graph``.

    Supports ``.ttl`` and ``.jsonld`` files.
    """
    _check_rdflib()
    from rdflib import Graph

    p = Path(path)
    g = Graph()
    suffix = p.suffix.lower()
    if suffix == ".ttl":
        g.parse(str(p), format="turtle")
    elif suffix in (".jsonld", ".json"):
        g.parse(str(p), format="json-ld")
    else:
        g.parse(str(p))
    return g


def load_all_shapes(shapes_dir: str | Path | None = None) -> Any:
    """
    Load and merge all shape files in a directory into one graph.

    Falls back to the built-in ``data/ontology/shapes/`` directory.
    """
    _check_rdflib()
    from rdflib import Graph

    d = Path(shapes_dir) if shapes_dir else _get_default_shapes_dir()
    merged = Graph()
    if not d.is_dir():
        return merged

    for p in sorted(d.iterdir()):
        if p.suffix.lower() in (".ttl", ".jsonld", ".json"):
            merged += load_shapes(p)

    return merged


def list_shapes(shapes_dir: str | Path | None = None) -> list[dict[str, str]]:
    """
    List available shape files with name and path.
    """
    d = Path(shapes_dir) if shapes_dir else _get_default_shapes_dir()
    if not d.is_dir():
        return []
    return [
        {"name": p.stem, "path": str(p)}
        for p in sorted(d.iterdir())
        if p.suffix.lower() in (".ttl", ".jsonld", ".json")
    ]
