"""
:mod:`etlplus.file.json` module.

Helpers for reading/writing JavaScript Object Notation (JSON) files.

Notes
-----
- A JSON file is a widely used data interchange format that uses
    human-readable text to represent structured data.
- Common cases:
    - Data interchange between web applications and servers.
    - Configuration files for applications.
    - Data storage for NoSQL databases.
- Rule of thumb:
    - If the file follows the JSON specification, use this module for
        reading and writing.
"""

from __future__ import annotations

import json

from ..types import JSONData
from ..types import StrPath
from ._io import call_deprecated_module_read
from ._io import call_deprecated_module_write
from ._io import coerce_record_payload
from .base import ReadOptions
from .base import SemiStructuredTextFileHandlerABC
from .base import WriteOptions
from .enums import FileFormat

# SECTION: EXPORTS ========================================================== #


__all__ = [
    # Classes
    'JsonFile',
    # Functions
    'read',
    'write',
]


# SECTION: CLASSES ========================================================== #


class JsonFile(SemiStructuredTextFileHandlerABC):
    """
    Handler implementation for JSON files.
    """

    # -- Class Attributes -- #

    format = FileFormat.JSON
    write_trailing_newline = True

    # -- Instance Methods -- #

    def dumps(
        self,
        data: JSONData,
        *,
        options: WriteOptions | None = None,
    ) -> str:
        """
        Serialize *data* to JSON text.

        Parameters
        ----------
        data : JSONData
            Payload to serialize.
        options : WriteOptions | None, optional
            Optional write parameters.

        Returns
        -------
        str
            Serialized JSON text.
        """
        _ = options
        return json.dumps(data, indent=2, ensure_ascii=False)

    def loads(
        self,
        text: str,
        *,
        options: ReadOptions | None = None,
    ) -> JSONData:
        """
        Parse JSON *text* into structured records.

        Parameters
        ----------
        text : str
            JSON payload as text.
        options : ReadOptions | None, optional
            Optional read parameters.

        Returns
        -------
        JSONData
            Parsed payload.
        """
        _ = options
        return coerce_record_payload(json.loads(text), format_name='JSON')


# SECTION: INTERNAL CONSTANTS =============================================== #

_JSON_HANDLER = JsonFile()


# SECTION: FUNCTIONS ======================================================== #


def read(
    path: StrPath,
) -> JSONData:
    """
    Deprecated wrapper. Use ``JsonFile().read(...)`` instead.

    Validates that the JSON root is a dict or a list of dicts.

    Parameters
    ----------
    path : StrPath
        Path to the JSON file on disk.

    Returns
    -------
    JSONData
        The structured data read from the JSON file.
    """
    return call_deprecated_module_read(
        path,
        __name__,
        _JSON_HANDLER.read,
    )


def write(
    path: StrPath,
    data: JSONData,
) -> int:
    """
    Deprecated wrapper. Use ``JsonFile().write(...)`` instead.

    Parameters
    ----------
    path : StrPath
        Path to the JSON file on disk.
    data : JSONData
        Data to serialize as JSON.

    Returns
    -------
    int
        The number of records written to the JSON file.
    """
    return call_deprecated_module_write(
        path,
        data,
        __name__,
        _JSON_HANDLER.write,
    )
