"""Agent entry point with guaranteed telemetry initialization."""

from __future__ import annotations

import logging
import pathlib
import re
import warnings
from typing import Optional, Union

logger = logging.getLogger(__name__)


def init_supervision(
    manifest: Union[str, pathlib.Path] = "manifest.yaml",
    otlp_config: Optional[dict] = None,  # backward compat, ignored
) -> None:
    """
    Initialize telemetry before any agent code runs.

    Call this at the very top of your task.py, BEFORE any other imports.
    This ensures OpenTelemetry is configured before any logging setup
    that might interfere with trace context propagation.

    Args:
        manifest: Path to the agent's manifest.yaml file.
        otlp_config: Deprecated. OTLP endpoint is now resolved by ObsConfig
            defaults and OTEL_EXPORTER_OTLP_ENDPOINT env var.

    Example:
        # task.py - FIRST LINE, before any other imports
        from thoughtful.supervisor import init_supervision; init_supervision()

        # Now safe to import other modules
        from libraries.logger import logger  # basicConfig(force=True) won't break traces
        from thoughtful.supervisor import supervise

        if __name__ == "__main__":
            with supervise():
                task()
    """
    if otlp_config is not None:
        warnings.warn(
            "otlp_config is deprecated and ignored. "
            "OTLP endpoint is configured via OTEL_EXPORTER_OTLP_ENDPOINT env var or ObsConfig defaults.",
            DeprecationWarning,
            stacklevel=2,
        )

    from t_obs import configure_observability, is_configured, ObsConfig

    from thoughtful.supervisor.telemetry.config import mark_telemetry_initialized_early
    from thoughtful.supervisor.manifest import Manifest
    from thoughtful.supervisor.telemetry.resources import extract_resource_attributes

    # Mark that we were called early (before checking if already configured)
    mark_telemetry_initialized_early()

    # Skip if already configured (idempotent — one-shot)
    if is_configured():
        return

    # Load manifest for service name
    manifest_obj = None
    manifest_path = pathlib.Path(manifest)
    if manifest_path.exists():
        try:
            manifest_obj = Manifest.from_file(manifest_path)
        except Exception as e:
            logger.warning("Could not load manifest: %s", e)

    raw_name = manifest_obj.uid if manifest_obj and manifest_obj.uid else "supervisor"
    # ObsConfig requires kebab-case; slugify the manifest UID
    service_name = re.sub(r"[^a-z0-9-]+", "-", raw_name.lower()).strip("-")

    configure_observability(
        service_name=service_name,
        config=ObsConfig(
            service_name=service_name,
            resource_attributes=extract_resource_attributes(),
        ),
    )
