"""
MuBit Learn Configuration.
"""

import os
from dataclasses import dataclass, field
from typing import List, Optional


@dataclass
class LearnConfig:
    """Configuration for the mubit.learn module."""

    # Connection
    api_key: Optional[str] = None
    endpoint: Optional[str] = None

    # Identity
    agent_id: str = "auto"
    user_id: str = ""
    session_id: Optional[str] = None  # None = auto-generate UUID

    # Lesson injection
    inject_lessons: bool = True
    injection_position: str = "system"  # "system" | "prepend" | "last_system"
    max_token_budget: int = 2048
    entry_types: Optional[List[str]] = None  # None = server default
    context_sections: Optional[List[str]] = None

    # Lane scoping
    lane: str = ""
    auto_extract: bool = True
    extraction_mode: str = "heuristic"

    # Ingestion (pass-through to auto module)
    capture: str = "all"  # "all" | "input_only" | "output_only"
    min_length: int = 0

    # Run lifecycle
    auto_reflect: bool = True
    reflect_after_n_calls: Optional[int] = None

    # Cache
    cache_ttl_seconds: float = 30.0
    cache_max_entries: int = 100

    # Safety
    fail_open: bool = True  # if get_context() fails, proceed without lessons

    def resolve(self) -> "LearnConfig":
        """Resolve env var fallbacks for api_key and endpoint."""
        if self.api_key is None:
            self.api_key = os.environ.get("MUBIT_API_KEY", "")
        if self.endpoint is None:
            self.endpoint = os.environ.get(
                "MUBIT_ENDPOINT", "http://127.0.0.1:3000"
            )
        self.endpoint = self.endpoint.rstrip("/")
        return self
