# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import json
from typing import IO, Any, cast


def read_json(file: IO[Any]) -> list[dict[str, str]]:
    """
    Read a JSON file and return its content.

    Returns:
        list[dict[str, str]]: Parsed JSON content.
    """
    return cast("list[dict[str, str]]", json.load(file))


def write_json(file: IO[Any], examples: list[dict[str, str]]) -> None:
    """
    Write a list of dictionaries to a JSON file.

    Args:
        file: A file-like object opened for writing JSON data.
        examples (list[dict[str, str]]): List of dictionaries to write as JSON.
    """
    json.dump(examples, file)


def read_jsonl(file: IO[Any]) -> list[dict[str, str]]:
    """
    Read a JSONL file and return its content.

    Returns:
        list[dict[str, str]]: Parsed JSONL content.
    """
    return [json.loads(line) for line in file if line.strip()]


def write_jsonl(file: IO[Any], examples: list[dict[str, str]]) -> None:
    """
    Write a list of dictionaries to a JSONL file.

    Args:
        file: A file-like object opened for writing JSONL data.
        examples (list[dict[str, str]]): List of dictionaries to write as JSONL.
    """
    for example in examples:
        file.write(json.dumps(example) + "\n")
