"""Bridge between the Acceldata-branded API surface and upstream Opik internals.

Everything in this module knows about the OPIK_* env-var names and the
upstream Opik configuration keys. Nothing outside this module should
reference them — that keeps the public package surface (__init__.py,
configure(), etc.) brand-clean.
"""

import os
import sys
from typing import Optional

from .auth import setup_acceldata_auth_hook
from ._http_debug import _install_http_debug_interceptor


# Customer-facing AIO env var name -> upstream Opik env var name.
# Upstream names are an internal implementation detail and never exposed
# in the public API.
_ALIASES = (
    ("URL",                   "ACCELDATA_AIO_URL",                   "OPIK_URL_OVERRIDE"),
    ("ACCESS_KEY",            "ACCELDATA_AIO_ACCESS_KEY",            "OPIK_ACCESS_KEY"),
    ("SECRET_KEY",            "ACCELDATA_AIO_SECRET_KEY",            "OPIK_SECRET_KEY"),
    ("PROJECT_NAME",          "ACCELDATA_AIO_PROJECT_NAME",          "OPIK_PROJECT_NAME"),
    ("CHECK_TLS_CERTIFICATE", "ACCELDATA_AIO_CHECK_TLS_CERTIFICATE", "OPIK_CHECK_TLS_CERTIFICATE"),
)


def _parse_truthy(value: str) -> bool:
    """True for common truthy string representations: 1, true, yes, on (case-insensitive)."""
    return value.strip().lower() in ("1", "true", "yes", "on")


def bootstrap_from_env() -> None:
    """Translate ACCELDATA_AIO_* env vars to the upstream names Opik reads
    natively, then auto-register the auth hook if creds are present and
    install the HTTP debug interceptor if ``ACCELDATA_AIO_DEBUG`` is truthy.

    An explicit upstream value (e.g. OPIK_URL_OVERRIDE) wins over its
    ACCELDATA_AIO_* counterpart — escape hatch for migration, ops scripts,
    or power-user overrides.

    Prints a one-line stderr summary listing which logical settings were
    configured. Brand-clean by design: it never names the underlying env
    var (which may be an internal OPIK_* name) nor any value.
    """
    picked = []
    for label, aio_name, upstream_name in _ALIASES:
        if os.environ.get(upstream_name) is not None:
            picked.append(label)
        elif os.environ.get(aio_name) is not None:
            os.environ[upstream_name] = os.environ[aio_name]
            picked.append(label)

    debug_raw = os.environ.get("ACCELDATA_AIO_DEBUG")
    debug_enabled = debug_raw is not None and _parse_truthy(debug_raw)
    if debug_enabled:
        picked.append("DEBUG")

    if picked:
        summary = ", ".join(picked)
        print(f"[acceldata_aio_tracer] env init: {summary} configured", file=sys.stderr)
    else:
        print(
            "[acceldata_aio_tracer] env init: no ACCELDATA_AIO_* or upstream "
            "env vars detected; call configure() to set explicitly",
            file=sys.stderr,
        )

    access_key = os.environ.get("OPIK_ACCESS_KEY")
    secret_key = os.environ.get("OPIK_SECRET_KEY")
    if access_key and secret_key:
        setup_acceldata_auth_hook(access_key, secret_key)

    if debug_enabled:
        url = os.environ.get("OPIK_URL_OVERRIDE")
        if url:
            _install_http_debug_interceptor(url)
        else:
            print(
                "[acceldata_aio_tracer] env init: ACCELDATA_AIO_DEBUG is truthy "
                "but no URL configured; debug interceptor not installed",
                file=sys.stderr,
            )


def apply_configure(
    *,
    url: str,
    access_key: str,
    secret_key: str,
    project_name: Optional[str],
    debug: bool,
    check_tls_certificate: bool,
) -> None:
    """Apply the side effects of a configure() call: write upstream env vars,
    register the Acceldata auth hook, optionally install the HTTP debug
    interceptor.
    """
    os.environ["OPIK_URL_OVERRIDE"] = url
    os.environ["OPIK_ACCESS_KEY"] = access_key
    os.environ["OPIK_SECRET_KEY"] = secret_key
    if project_name is not None:
        os.environ["OPIK_PROJECT_NAME"] = project_name
    setup_acceldata_auth_hook(access_key, secret_key)
    os.environ["OPIK_CHECK_TLS_CERTIFICATE"] = "true" if check_tls_certificate else "false"
    if debug:
        _install_http_debug_interceptor(url)


def apply_configure_multitenant(
    *,
    url: str,
    project_name: Optional[str],
    debug: bool,
    check_tls_certificate: bool,
    service_tenant: Optional[object] = None,
) -> None:
    """Apply the side effects of a configure_multitenant_client() call.

    Parallel to :func:`apply_configure` but for multi-tenant deployments:
    the gateway-level apiKey auth is bypassed, so we do NOT set
    ``OPIK_ACCESS_KEY`` / ``OPIK_SECRET_KEY``, and we install
    :class:`MultiTenantAuth` instead of :class:`AcceldataAuth` on every
    Opik httpx client.

    Tenant identity is then read from a per-thread thread-local set by
    the wrapper's processor patch on each server-bound REST call.
    """
    # Late import to avoid a top-level cycle: multitenant_auth imports
    # opik at module load, which is already paid for by other paths,
    # but keeping it lazy mirrors how _install_http_debug_interceptor
    # is wired and lets the bridge stay import-time light.
    from .multitenant_auth import setup_multitenant_auth_hook

    os.environ["OPIK_URL_OVERRIDE"] = url
    if project_name is not None:
        os.environ["OPIK_PROJECT_NAME"] = project_name
    os.environ["OPIK_CHECK_TLS_CERTIFICATE"] = "true" if check_tls_certificate else "false"
    setup_multitenant_auth_hook(service_tenant=service_tenant)
    if debug:
        _install_http_debug_interceptor(url)
