"""Background logging service for sending requests to Mandatum API."""

import json
import threading
import time
from queue import Queue
from typing import Any, Dict, Optional
import httpx


class LoggingService:
    """
    Asynchronous logging service for Mandatum.

    Queues log events and sends them in background threads to avoid
    blocking LLM API calls.
    """

    def __init__(
        self,
        api_key: str,
        base_url: str,
        organization_id: Optional[str] = None,
        debug: bool = False,
    ):
        self.api_key = api_key
        self.base_url = base_url
        self.organization_id = organization_id
        self.debug = debug

        self.queue: Queue = Queue()
        self.running = True
        self.worker_thread = threading.Thread(target=self._worker, daemon=True)
        self.worker_thread.start()

    def log_request(
        self,
        provider: str,
        model: str,
        request_data: Dict[str, Any],
        response_data: Dict[str, Any],
        latency_ms: int,
        input_tokens: int,
        output_tokens: int,
        cost: float,
        environment: Optional[str] = None,
        tags: Optional[list] = None,
        metadata: Optional[Dict[str, Any]] = None,
        prompt_id: Optional[str] = None,
        error: Optional[str] = None,
    ):
        """Queue a request to be logged to Mandatum."""
        log_entry = {
            "provider": provider,
            "model": model,
            "request_data": request_data,
            "response_data": response_data,
            "latency_ms": latency_ms,
            "input_tokens": input_tokens,
            "output_tokens": output_tokens,
            "cost": cost,
            "environment": environment,
            "tags": tags or [],
            "metadata": metadata or {},
            "prompt_id": prompt_id,
            "error": error,
        }

        if self.debug:
            print(f"[Mandatum] Queuing log entry: {log_entry}")

        self.queue.put(log_entry)

    def _worker(self):
        """Background worker that processes the log queue."""
        while self.running:
            try:
                if not self.queue.empty():
                    log_entry = self.queue.get(timeout=1)
                    self._send_to_api(log_entry)
                else:
                    time.sleep(0.1)
            except Exception as e:
                if self.debug:
                    print(f"[Mandatum] Error in logging worker: {e}")

    def _send_to_api(self, log_entry: Dict[str, Any]):
        """Send log entry to Mandatum API via /track-request endpoint."""
        try:
            # Construct URL - ensure we have /api/v1 prefix if not already present
            base = self.base_url
            if not base.endswith('/api/v1'):
                base = f"{base}/api/v1"
            url = f"{base}/llm/track-request"

            headers = {
                "X-API-Key": self.api_key,
                "Content-Type": "application/json",
            }

            payload = {
                "provider": log_entry["provider"],
                "model": log_entry["model"],
                "messages": log_entry["request_data"].get("messages", []),
                "response": log_entry["response_data"].get("content", ""),
                "input_tokens": log_entry["input_tokens"],
                "output_tokens": log_entry["output_tokens"],
                "cost": log_entry["cost"],
                "latency_ms": log_entry["latency_ms"],
                "temperature": log_entry["request_data"].get("temperature"),
                "max_tokens": log_entry["request_data"].get("max_tokens"),
                "environment": log_entry["environment"],
                "tags": log_entry["tags"] or [],
                "metadata": log_entry["metadata"] or {},
                "status": "error" if log_entry["error"] else "success",
                "error_message": log_entry["error"],
            }

            if log_entry["prompt_id"]:
                payload["prompt_id"] = log_entry["prompt_id"]

            with httpx.Client(timeout=5.0) as client:
                response = client.post(url, json=payload, headers=headers)
                response.raise_for_status()

                if self.debug:
                    response_data = response.json()
                    print(f"[Mandatum] Successfully logged request: {response_data.get('request_id')}")

        except Exception as e:
            if self.debug:
                print(f"[Mandatum] Failed to send log to API: {e}")

    def shutdown(self):
        """Shutdown the logging service and wait for queue to empty."""
        self.running = False
        while not self.queue.empty():
            time.sleep(0.1)
        self.worker_thread.join(timeout=5)
