import os
import logging
from typing import Optional
from .structured_log import configure_logging, get_logger
from .log_shipper import LogShipper

# Module-level reference so __main__.py can start/stop the shipper
_log_shipper: Optional[LogShipper] = None


def get_log_shipper() -> Optional[LogShipper]:
    """Get the active log shipper instance (None for cloud runners)."""
    return _log_shipper


def setup_logger(level: str = "INFO", api_url: str = ""):
    """Set up structured logging.

    Both local and cloud runners default to JSON output (production).
    Set SKOP_LOG_FORMAT=console for human-readable colored output (debugging only).

    Local runners: installs a LogShipper processor that captures log entries
    for HTTP shipping to /api/logs. Call get_log_shipper().start() after the
    event loop is running.
    """
    global _log_shipper
    use_console = os.getenv("SKOP_LOG_FORMAT", "").lower() == "console"
    is_cloud = os.getenv("SKOP_CLOUD_RUNNER") == "true"

    extra_processors = []
    if not is_cloud and api_url:
        _log_shipper = LogShipper(api_url=api_url)
        extra_processors.append(_log_shipper.capture)

    configure_logging(
        level=level,
        json_output=not use_console,
        extra_processors=extra_processors,
    )
    return logging.getLogger("skop-runner")
