"""
MuBit Learn Client.

Lightweight urllib-based HTTP client for get_context() and reflect().
Follows the IngestWorker._post_ingest() pattern — no external deps.
"""

import json
import logging
import urllib.request
import urllib.error
from typing import List, Optional

logger = logging.getLogger("mubit.learn")


class LearnClient:
    """Minimal HTTP client for context retrieval and reflection."""

    def __init__(self, api_key: str, endpoint: str):
        self._api_key = api_key
        self._endpoint = endpoint.rstrip("/")

    def get_context(
        self,
        session_id: str,
        query: str,
        max_token_budget: int = 2048,
        entry_types: Optional[List[str]] = None,
        sections: Optional[List[str]] = None,
        lane_filter: Optional[str] = None,
    ) -> str:
        """Fetch assembled context block from the server.

        Returns the context_block string, or empty string on failure.
        """
        payload = {
            "run_id": session_id,
            "query": query,
            "format": "structured",
            "max_token_budget": max_token_budget,
        }
        if entry_types:
            payload["entry_types"] = entry_types
        if sections:
            payload["sections"] = sections
        if lane_filter:
            payload["lane"] = lane_filter

        try:
            resp = self._post("/v2/control/context", payload)
            return resp.get("context_block", "")
        except Exception as e:
            logger.debug("mubit.learn get_context failed (non-fatal): %s", e)
            return ""

    def reflect(
        self,
        session_id: str,
        step_id: Optional[str] = None,
        checkpoint_id: Optional[str] = None,
        last_n_items: Optional[int] = None,
    ) -> None:
        """Trigger reflection for a session. Fire-and-forget."""
        try:
            payload = {"run_id": session_id}
            if step_id:
                payload["step_id"] = step_id
            if checkpoint_id:
                payload["checkpoint_id"] = checkpoint_id
            if last_n_items:
                payload["last_n_items"] = last_n_items
            self._post("/v2/control/reflect", payload)
        except Exception as e:
            logger.debug("mubit.learn reflect failed (non-fatal): %s", e)

    def _post(self, path: str, payload: dict) -> dict:
        if not self._api_key:
            return {}

        body = json.dumps(payload).encode("utf-8")
        url = f"{self._endpoint}{path}"

        req = urllib.request.Request(
            url,
            data=body,
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self._api_key}",
                "User-Agent": "mubit-sdk-python-learn/0.1.0",
            },
            method="POST",
        )

        with urllib.request.urlopen(req, timeout=5) as response:
            if response.status >= 400:
                logger.debug("mubit.learn HTTP %d for %s", response.status, path)
                return {}
            return json.loads(response.read().decode("utf-8"))
