"""
LangSmith metadata exporter for releaseops.

Attaches releaseops telemetry metadata to LangSmith runs
for later querying and attribution.
"""

from __future__ import annotations

import logging
import os
from typing import Any, Dict, List, Optional

logger = logging.getLogger(__name__)

LANGSMITH_API_BASE = "https://api.smith.langchain.com"


class LangSmithExporter:
    """
    Exports releaseops metadata to LangSmith runs.

    Requires httpx (install with: pip install llmhq-releaseops[langsmith]).
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        api_base: Optional[str] = None,
    ) -> None:
        self._api_key = api_key or os.environ.get("LANGSMITH_API_KEY", "")
        self._api_base = api_base or os.environ.get("LANGSMITH_ENDPOINT", LANGSMITH_API_BASE)

    def _get_client(self):
        """Lazy-import httpx and return a configured client."""
        try:
            import httpx
        except ImportError:
            raise ImportError(
                "httpx is required for LangSmith integration. "
                "Install with: pip install llmhq-releaseops[langsmith]"
            )
        return httpx.Client(
            base_url=self._api_base,
            headers={"x-api-key": self._api_key},
            timeout=30.0,
        )

    def export_run_metadata(self, metadata, run_id: str) -> None:
        """
        Attach releaseops metadata to a LangSmith run.

        Args:
            metadata: TelemetryContext with bundle metadata.
            run_id: LangSmith run ID to update.
        """
        flat = metadata.to_flat_dict()
        client = self._get_client()
        try:
            response = client.patch(
                f"/api/v1/runs/{run_id}",
                json={
                    "extra": {
                        "metadata": flat,
                    }
                },
            )
            response.raise_for_status()
            logger.info(f"Exported metadata to LangSmith run {run_id}")
        except Exception as e:
            logger.error(f"Failed to export metadata to run {run_id}: {e}")
            raise
        finally:
            client.close()

    def tag_run(self, run_id: str, tags: List[str]) -> None:
        """
        Add tags to a LangSmith run for filtering.

        Args:
            run_id: LangSmith run ID to tag.
            tags: List of tag strings.
        """
        client = self._get_client()
        try:
            response = client.patch(
                f"/api/v1/runs/{run_id}",
                json={"tags": tags},
            )
            response.raise_for_status()
            logger.info(f"Tagged LangSmith run {run_id} with {tags}")
        except Exception as e:
            logger.error(f"Failed to tag run {run_id}: {e}")
            raise
        finally:
            client.close()
