"""Optional local LLM command classifier for GAR-BOT."""

from __future__ import annotations

import json
import logging
import urllib.request

LOG = logging.getLogger(__name__)


class LocalLLM:
    """Tiny Ollama-compatible helper.

    The LLM is never allowed to drive hardware directly. It can only translate
    natural language into a short phrase that is then parsed by the allow-listed
    rule brain.
    """

    def __init__(self, enabled: bool, url: str, model: str):
        self.enabled = enabled
        self.url = url
        self.model = model

    def classify(self, text: str) -> str:
        if not self.enabled:
            return text
        prompt = (
            "You control K2Aley GAR-BOT. Convert the user request into exactly "
            "one safe command phrase from this list: stop, forward, reverse, "
            "left, right, open left claw, open right claw, open both claws, "
            "close left claw, close right claw, close both claws, home both claws, "
            "status. Return only the command phrase.\n\n"
            f"User request: {text}"
        )
        payload = json.dumps(
            {"model": self.model, "prompt": prompt, "stream": False}
        ).encode("utf-8")
        try:
            req = urllib.request.Request(
                self.url,
                data=payload,
                headers={"Content-Type": "application/json"},
                method="POST",
            )
            with urllib.request.urlopen(req, timeout=2.0) as response:
                body = json.loads(response.read().decode("utf-8"))
            return str(body.get("response", text)).strip().splitlines()[0]
        except Exception:
            LOG.exception("Local LLM unavailable; falling back to rule parser")
            return text
