"""
Machine-readable JSON output for AI agent consumption.

When --machine is active, all CLI commands use these helpers
instead of Rich tables/panels. Output goes to stdout as JSON
(single object) or JSONL (one event per line for streaming).
"""

import json
import sys
from datetime import UTC, datetime
from typing import Any


def _serialize(obj: Any) -> Any:
    """JSON serializer for objects not handled by default."""
    if isinstance(obj, datetime):
        return obj.isoformat()
    if hasattr(obj, "model_dump"):
        return obj.model_dump()
    if hasattr(obj, "dict"):
        return obj.dict()
    return str(obj)


def emit_json(data: dict) -> None:
    """Print a single JSON object to stdout (for non-streaming commands)."""
    print(json.dumps(data, default=_serialize, ensure_ascii=False))


def emit_jsonl(event_type: str, data: dict) -> None:
    """Print a single JSONL line to stdout (for streaming commands).

    Format: {"event": "<type>", "timestamp": "...", ...data}
    """
    record = {
        "event": event_type,
        "timestamp": datetime.now(UTC).isoformat(),
        **data,
    }
    print(json.dumps(record, default=_serialize, ensure_ascii=False), flush=True)


def emit_error(code: str, message: str, suggestion: str = "") -> None:
    """Print a structured error to stdout."""
    err = {"error": code, "message": message}
    if suggestion:
        err["suggestion"] = suggestion
    print(json.dumps(err, ensure_ascii=False), file=sys.stderr)


def is_machine(args) -> bool:
    """Check if --machine flag is set."""
    return getattr(args, "machine", False)
