"""Anthropic SDK client factory ve sistem prompt yükleme."""

from __future__ import annotations

from functools import lru_cache
from pathlib import Path

from anthropic import AsyncAnthropic

from app.config import get_settings


class LLMClientError(Exception):
    """LLM tarafında recoverable hatalar için base exception."""


class LLMNotConfiguredError(LLMClientError):
    """ANTHROPIC_API_KEY yoksa fırlatılır."""


_PROMPT_PATH = Path(__file__).resolve().parent.parent.parent / "prompts" / "turkpatent.md"


@lru_cache
def load_turkpatent_system_prompt() -> str:
    """TürkPatent format kurallarını içeren sistem prompt'unu okur.

    Bu dosya prompt caching için stable bir prefix olmalı — değişirse cache
    invalidate olur (bkz. CLAUDE.md "LLM cost discipline").
    """
    if not _PROMPT_PATH.exists():
        raise LLMClientError(f"TürkPatent prompt bulunamadı: {_PROMPT_PATH}")
    return _PROMPT_PATH.read_text(encoding="utf-8")


@lru_cache
def get_anthropic_client() -> AsyncAnthropic:
    """Global AsyncAnthropic client. API key yoksa LLMNotConfiguredError."""
    settings = get_settings()
    if not settings.anthropic_api_key:
        raise LLMNotConfiguredError(
            "ANTHROPIC_API_KEY tanımlı değil. backend-python/.env dosyasına ekleyin."
        )
    return AsyncAnthropic(api_key=settings.anthropic_api_key)
