"""
Cliente HTTP interno do SDK ONEROM.

Encapsula todas as chamadas ao runner-agent API.
Autenticacao via X-Runner-Key (injetado pelo runner como ONEROM_RUNNER_KEY).

Se ONEROM_API_URL ou ONEROM_RUNNER_KEY nao estiverem disponiveis,
o cliente opera em modo passivo (sem chamadas HTTP) — o runner
ja gerencia o ciclo de vida da execucao via metrics file e stdout.
"""
import logging
import os
from typing import Any

logger = logging.getLogger(__name__)


class OneromClient:
    """
    Cliente HTTP para a API runner-agent do ONEROM.

    Todas as chamadas falham silenciosamente — nunca propagam excecoes.
    O runner e responsavel pelo status final via metrics file.
    """

    def __init__(self) -> None:
        self.api_url = os.environ.get("ONEROM_API_URL", "").rstrip("/")
        self.runner_key = os.environ.get("ONEROM_RUNNER_KEY", "")
        self.available = bool(self.api_url and self.runner_key)

        raw_id = os.environ.get("ONEROM_EXECUTION_ID")
        if raw_id is None:
            raise RuntimeError(
                "ONEROM_EXECUTION_ID nao definido. "
                "Este SDK deve ser executado dentro do ONEROM Runner."
            )
        self.execution_id = int(raw_id)

        if not self.available:
            logger.debug(
                "ONEROM_API_URL ou ONEROM_RUNNER_KEY ausentes — "
                "cliente HTTP desabilitado (modo passivo)"
            )

    def put_execution(self, status: str, **kwargs: Any) -> None:
        """
        Atualiza status da execucao no backend.

        Args:
            status: RUNNING | SUCCESS | FAILED | TIMEOUT
            **kwargs: Campos opcionais (items_processed, items_failed,
                      error_message, error_traceback, log_output, started_at)
        """
        if not self.available:
            return

        try:
            import requests

            payload: dict[str, Any] = {"status": status}
            for key, value in kwargs.items():
                if value is not None:
                    payload[key] = value

            resp = requests.put(
                f"{self.api_url}/api/v1/runner-agent/executions/{self.execution_id}",
                json=payload,
                headers={"X-Runner-Key": self.runner_key},
                timeout=10,
            )

            if resp.status_code not in (200, 204):
                logger.debug(
                    f"put_execution retornou {resp.status_code}: {resp.text[:200]}"
                )

        except Exception as exc:
            # Nunca propaga — o runner cobre o status via metrics file
            logger.debug(f"put_execution falhou silenciosamente: {exc}")
