"""json5rt — JSON5 round-trip library: load, edit, and save JSON5 files with comment preservation.

Provides a clean, simple API for working with JSON5/JSON/JSONC files that
preserves comments and whitespace through read → edit → write cycles.

Uses json-five internally but exposes a non-colliding import name (``json5rt``)
to avoid the ``json5`` import name collision between the ``json5`` and
``json-five`` PyPI packages.

Usage::

    import json5rt

    # Load a JSON5 file with comments
    doc = json5rt.load("config.json5")

    # Edit like a dict
    doc["port"] = 9090
    doc["ssl"] = False
    del doc["features"]

    # Save back — comments preserved!
    doc.save()

    # Or use the functional API
    text = json5rt.dumps(doc)

    # Create from scratch
    doc = json5rt.Document()
    doc["host"] = "localhost"
    doc.save("new_config.json")  # valid JSON (double-quoted, no comments)
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

from json5.loader import ModelLoader

from ._document import Document

__version__ = "0.1.0"

__all__ = ["load", "loads", "dump", "dumps", "Document"]


def load(path: str | Path) -> Document:
    """Load a JSON5/JSON/JSONC file with comment preservation.

    Args:
        path: Path to the file to load.

    Returns:
        A :class:`Document` that acts like a dict and preserves comments.

    Example::

        doc = json5rt.load("config.json5")
        print(doc["host"])  # → "localhost"
    """
    import json5
    p = Path(path)
    with p.open(encoding="utf-8") as f:
        model = json5.load(f, loader=ModelLoader())
    return Document(model=model, source_path=p)


def loads(text: str) -> Document:
    """Load a JSON5/JSON/JSONC string with comment preservation.

    Args:
        text: JSON5/JSON/JSONC text to parse.

    Returns:
        A :class:`Document` that acts like a dict and preserves comments.

    Example::

        doc = json5rt.loads('{ // comment\\n  "port": 8080\\n}')
        doc["port"] = 9090
        print(json5rt.dumps(doc))  # comment preserved
    """
    from json5.loader import loads as _loads
    model = _loads(text, loader=ModelLoader())
    return Document(model=model)


def dump(doc: Document, path: str | Path) -> Path:
    """Write a Document to a file with comments preserved.

    Args:
        doc: The :class:`Document` to write.
        path: File path to write to.

    Returns:
        The path the document was written to.

    Example::

        json5rt.dump(doc, "config.json5")
    """
    return doc.save(path)


def dumps(doc: Document) -> str:
    """Serialize a Document to a string with comments preserved.

    Args:
        doc: The :class:`Document` to serialize.

    Returns:
        The JSON5/JSONC text with comments preserved.

    Example::

        text = json5rt.dumps(doc)
    """
    return doc.dumps()
