"""Proxy AI provider — routes requests through MuraveyChina license server.

The Worker at muraveychina-license.muravey-license.workers.dev forwards
requests to Deepseek or Aliyun based on model name, using server-side API keys.
The client authenticates with its license token (no personal API key required).

Usage:
    provider = ProxyProvider(base_url=PROXY_BASE_URL, session_key="<token>")
    response = provider.ask(AIRequest(prompt="Hello", model="deepseek-chat"))
"""

from __future__ import annotations

import logging
import threading

import openai

from .base import AIProvider
from .base_provider import BaseAPIProvider

log = logging.getLogger(__name__)

PROXY_BASE_URL = "https://license.muravey.app/v1"


class ProxyProvider(BaseAPIProvider, AIProvider):
    """License-authenticated AI proxy provider.

    Sends requests to the MuraveyChina Worker which forwards them to
    Deepseek or Aliyun using server-side API keys. Requires an active
    license session_key as Bearer token.
    """

    name = "proxy"
    DEFAULT_MODEL = "deepseek-chat"

    def __init__(self, session_key: str, base_url: str = PROXY_BASE_URL, proxy_url: str = "") -> None:
        self._base_url = base_url.rstrip("/")
        self._session_key = session_key
        self._proxy_url = proxy_url
        self._client: openai.OpenAI | None = None
        self._client_lock = threading.Lock()
        self.api_key = session_key
        self._auth_failed = False  # cached 401 — skip on subsequent calls

    def is_available(self) -> bool:
        return bool(self._session_key) and not self._auth_failed

    def _create_client(self) -> openai.OpenAI:
        kwargs = dict(
            api_key=self._session_key,
            base_url=self._base_url,
            timeout=30.0,
            max_retries=0,
        )
        http_client = self._make_http_client(timeout=30.0)
        if http_client:
            kwargs["http_client"] = http_client
        return openai.OpenAI(**kwargs)

    def ask(self, request):
        """Override to cache 401 auth failures — avoids wasting time on expired tokens."""
        try:
            return super().ask(request)
        except openai.AuthenticationError:
            self._auth_failed = True
            log.warning("[proxy] Authentication failed (401) — disabling proxy provider")
            raise
