from __future__ import annotations

import json
import os
from typing import Any
from urllib import request


class IngestClient:
    def __init__(self, api_url: str, api_key: str | None = None, timeout_seconds: float = 5.0) -> None:
        self.api_url = api_url.rstrip("/")
        self.api_key = api_key
        self.timeout_seconds = timeout_seconds

    @classmethod
    def from_env(cls) -> IngestClient | None:
        api_url = os.getenv("AGENTTRACE_API_URL")
        if not api_url:
            return None
        api_key = os.getenv("AGENTTRACE_API_KEY")
        return cls(api_url=api_url, api_key=api_key)

    def ingest(self, payload: dict[str, Any]) -> None:
        data = json.dumps(payload).encode("utf-8")
        url = f"{self.api_url}/v1/ingest"
        headers = {"Content-Type": "application/json"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        req = request.Request(url=url, data=data, headers=headers, method="POST")
        with request.urlopen(req, timeout=self.timeout_seconds):
            return

    async def async_ingest(self, payload: dict[str, Any]) -> None:
        import aiohttp

        data = json.dumps(payload).encode("utf-8")
        url = f"{self.api_url}/v1/ingest"
        headers = {"Content-Type": "application/json"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        async with aiohttp.ClientSession() as session:
            async with session.post(
                url, data=data, headers=headers, timeout=aiohttp.ClientTimeout(total=self.timeout_seconds)
            ):
                return
