#
#   Imandra Inc.
#
#   utils/__init__.py
#

from __future__ import annotations

import os
import json
import typer
from typing import Any, TypeAlias
from enum import Enum, StrEnum
from rich.console import Console
from rich.theme import Theme

IMANDRA_KEY_ENV = "IMANDRA_UNI_KEY"


console = Console(
    force_terminal=True, 
    color_system="truecolor", 
    theme=Theme({"info": "cyan", "ok": "green", "warn": "yellow", "err": "red"})
)

class IMLValidity (StrEnum):
    VALID = 'valid'
    INVALID = 'invalid'
    UNKNOWN = 'unknown'


JSONScalar: TypeAlias = str | int | float | bool | None
JSONValue: TypeAlias = JSONScalar | list["JSONValue"] | dict[str, "JSONValue"]
JSONObject: TypeAlias = dict[str, JSONValue]


def emit_json(obj: JSONObject) -> None:
    """
    Print JSON (never exits).
    Use this only at the CLI boundary or for debugging.
    """
    typer.echo(json.dumps(obj, indent=2, default=_json_default))


def _json_default(o: Any) -> Any:
    # Enums (BaseStatus, PredicateType, etc)
    if isinstance(o, Enum):
        return o.value
    # datetime, Path, etc (best-effort string)
    try:
        return str(o)
    except Exception:
        return repr(o)

def require_imandra_key() -> None:
    """
    Ensure IMANDRA_UNI_KEY is present in the environment.
    Exit the CLI with a clear message if not.
    """
    key = os.getenv(IMANDRA_KEY_ENV)

    if not key:
        console.print(
            "[red]✖ ImandraX API key missing[/red]\n\n"
            "SpecLogician requires an Imandra Universe API key to run.\n\n"
            "Please set the environment variable:\n\n"
            f"  export {IMANDRA_KEY_ENV}=<your-api-key>\n\n"
            "You can obtain a key from Imandra Universe."
        )
        raise typer.Exit(code=2)

__all__ = [
    "require_imandra_key",
    "emit_json",
    "_json_default",
    "IMLValidity",
    "console"
]