"""
Format converter -- JSON-LD <-> Turtle via an rdflib Graph intermediary.

All functions require ``rdflib`` (installed via the ``ontology`` extra).
"""

from __future__ import annotations

import json
from typing import Any

from pycharter.wiki.rdf import _check_rdflib
from pycharter.wiki.rdf.context import JSONLD_CONTEXT


def jsonld_to_graph(data: dict[str, Any]) -> Any:
    """Parse a JSON-LD dict into an ``rdflib.Graph``."""
    _check_rdflib()
    from rdflib import Graph

    g = Graph()
    g.parse(data=json.dumps(data), format="json-ld")
    return g


def graph_to_jsonld(graph: Any, context: dict | None = None) -> dict[str, Any]:
    """Serialize an ``rdflib.Graph`` to a compacted JSON-LD dict."""
    _check_rdflib()
    raw = graph.serialize(format="json-ld")
    doc = json.loads(raw)
    ctx = context or JSONLD_CONTEXT
    if isinstance(doc, list):
        return {"@context": ctx, "@graph": doc}
    if isinstance(doc, dict) and "@context" not in doc:
        doc["@context"] = ctx
    return doc


def jsonld_to_ttl(data: dict[str, Any]) -> str:
    """Convert a JSON-LD dict to a Turtle string."""
    g = jsonld_to_graph(data)
    return g.serialize(format="turtle")


def ttl_to_graph(ttl: str) -> Any:
    """Parse a Turtle string into an ``rdflib.Graph``."""
    _check_rdflib()
    from rdflib import Graph

    g = Graph()
    g.parse(data=ttl, format="turtle")
    return g


def ttl_to_jsonld(ttl: str, context: dict | None = None) -> dict[str, Any]:
    """Convert a Turtle string to a JSON-LD dict."""
    g = ttl_to_graph(ttl)
    return graph_to_jsonld(g, context=context)
