import os

import requests

DEFAULT_TIMEOUT_SECONDS = 10
DEFAULT_RETRIES = 2


def _base_url() -> str:
    return os.getenv("LOGMERA_URL", "http://127.0.0.1:8000").rstrip("/")


def log(
    project_id: str,
    prompt: str,
    response: str,
    model: str,
    latency_ms: int | None = None,
    status: str | None = None,
) -> bool:
    """Send one observability log to Logmera."""
    payload = {
        "project_id": project_id,
        "prompt": prompt,
        "response": response,
        "model": model,
        "latency_ms": latency_ms,
        "status": status,
    }

    required = ("project_id", "prompt", "response", "model")
    missing = [key for key in required if not payload[key]]
    if missing:
        raise ValueError(f"Missing required log fields: {', '.join(missing)}")

    timeout = int(os.getenv("LOGMERA_TIMEOUT_SECONDS", str(DEFAULT_TIMEOUT_SECONDS)))
    retries = int(os.getenv("LOGMERA_RETRIES", str(DEFAULT_RETRIES)))
    url = f"{_base_url()}/logs"

    last_error: Exception | None = None
    for _ in range(retries + 1):
        try:
            resp = requests.post(url, json=payload, timeout=timeout)
            resp.raise_for_status()
            return True
        except Exception as exc:  
            last_error = exc

    print(f"[logmera-sdk] failed to send log: {last_error}")
    return False
