"""JSON I/O utilities for stdin/stdout operations using msgspec."""

from __future__ import annotations

import json
import sys
from typing import Any

import msgspec


def read_json_stdin() -> dict[str, Any]:
    """Read JSON from stdin.

    Returns:
        Parsed JSON object

    Raises:
        ValueError: If JSON parsing fails
    """
    try:
        data = sys.stdin.buffer.read()
        if not data:
            raise ValueError("No JSON input on stdin")
        result = msgspec.json.decode(data)
        if isinstance(result, dict):
            return result
        raise ValueError("Expected JSON object at top level")
    except Exception as e:
        raise ValueError(f"Failed to parse JSON from stdin: {e}")


def write_json_stdout(obj: Any, compact: bool = True) -> None:
    """Write JSON to stdout.

    Args:
        obj: Object to serialize
        compact: Use compact formatting (default True)
    """
    data = msgspec.json.encode(obj)
    sys.stdout.buffer.write(data)
    sys.stdout.buffer.write(b"\n")
    sys.stdout.buffer.flush()


def write_json_stderr(obj: Any) -> None:
    """Write JSON to stderr (for errors).

    Args:
        obj: Object to serialize
    """
    json.dump(obj, sys.stderr, indent=2)
    sys.stderr.write("\n")
    sys.stderr.flush()
