"""Output helpers for the mgf-cloud CLI.

``emit`` renders a value either as pretty JSON (``--json``) or a compact
human line/block. Resource models are pydantic, so JSON is their ``model_dump``.
"""

from __future__ import annotations

import json
from typing import Any

from pydantic import BaseModel

__all__ = ["emit", "to_jsonable"]


def to_jsonable(obj: Any) -> Any:
    """Convert models / lists / dicts into JSON-serialisable plain data."""
    if isinstance(obj, BaseModel):
        return obj.model_dump(mode="json")
    if isinstance(obj, (list, tuple)):
        return [to_jsonable(item) for item in obj]
    if isinstance(obj, dict):
        return {key: to_jsonable(value) for key, value in obj.items()}
    return obj


def _compact(model: BaseModel) -> str:
    parts = [
        f"{key}={value}"
        for key, value in model.model_dump().items()
        if value not in ((), [], {}, "", None)
    ]
    return "  ".join(parts) if parts else "(empty)"


def emit(obj: Any, *, as_json: bool) -> None:
    """Print ``obj`` as JSON (``as_json``) or a compact human rendering."""
    if as_json:
        print(json.dumps(to_jsonable(obj), indent=2, sort_keys=True))
        return
    if isinstance(obj, (list, tuple)):
        if not obj:
            print("(none)")
            return
        for item in obj:
            print(_compact(item) if isinstance(item, BaseModel) else str(item))
        return
    if isinstance(obj, BaseModel):
        print(_compact(obj))
        return
    print(obj)
