"""Logging setup for worai CLI."""

from __future__ import annotations

import logging
import os
import sys
from typing import Literal


LogFormat = Literal["text", "json"]


def _is_truthy(value: str | None) -> bool:
    if value is None:
        return False
    return value.strip().lower() in {"1", "true", "yes", "on"}


def _configure_noisy_loggers() -> None:
    gql_logger = logging.getLogger("gql.transport.aiohttp")
    if _is_truthy(os.environ.get("WORAI_DEBUG_GRAPHQL_PAYLOADS")):
        gql_logger.setLevel(logging.NOTSET)
        return
    gql_logger.setLevel(logging.WARNING)


def setup_logging(level: str = "info", fmt: LogFormat = "text", quiet: bool = False) -> None:
    if quiet:
        level = "warning"
    level_value = getattr(logging, level.upper(), logging.INFO)
    handler = logging.StreamHandler(sys.stderr)
    handler.setLevel(level_value)
    if fmt != "json":
        handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))

    # Reconfigure root logging deterministically at CLI startup so third-party
    # logger setup cannot leak lower-severity messages through existing handlers.
    logging.basicConfig(level=level_value, handlers=[handler], force=True)
    _configure_noisy_loggers()
