# backend/app/llm/provider.py
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass

from ..config import get_settings


@dataclass
class Classification:
    type: str  # task | event | idea
    sphere: str  # work | life
    project_id: str | None = None
    proj_label: str = ""
    tone: str = "ink"
    due_text: str = ""
    when_text: str = ""
    extra: str = ""
    reason: str = ""  # 한국어
    confidence: float = 0.0
    model: str = ""


class LLMProvider(ABC):
    name: str = "base"

    @abstractmethod
    def health(self) -> dict: ...

    @abstractmethod
    def generate_json(self, prompt: str, schema: dict | None = None) -> dict: ...

    @abstractmethod
    def classify_capture(self, raw: str, context: dict) -> Classification: ...


_cached: LLMProvider | None = None


def get_provider(force: str | None = None) -> LLMProvider:
    """LLM_PROVIDER=auto|ollama|heuristic. auto면 ollama health 확인 후 폴백."""
    global _cached
    from .heuristic import HeuristicProvider
    from .ollama import OllamaProvider

    mode = force or get_settings().llm_provider
    if mode == "heuristic":
        return HeuristicProvider()
    if mode == "ollama":
        return OllamaProvider()
    # auto
    ollama = OllamaProvider()
    if ollama.health().get("reachable"):
        return ollama
    return HeuristicProvider()


def reset_provider_cache():
    global _cached
    _cached = None
