"""Configuration loading for K2Aley GAR-BOT."""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class MotorPins:
    rpwm: int
    lpwm: int
    r_en: int
    l_en: int


@dataclass
class AgentConfig:
    robot_name: str = "K2Aley GAR-BOT"
    hardware_enabled: bool = False
    max_speed: float = 0.45
    turn_speed: float = 0.35
    command_timeout_s: float = 1.5
    http_host: str = "0.0.0.0"
    http_port: int = 8080
    left_claw_device: str = "/dev/ttyACM0"
    right_claw_device: str = "/dev/ttyACM1"
    lora_device: str = "/dev/serial0"
    lora_baud: int = 115200
    ollama_enabled: bool = False
    ollama_url: str = "http://127.0.0.1:11434/api/generate"
    ollama_model: str = "llama3.2:1b"
    motor_pins: dict[str, MotorPins] = field(default_factory=dict)


def load_config(path: str | Path) -> AgentConfig:
    data = json.loads(Path(path).read_text(encoding="utf-8"))
    pins = {
        name: MotorPins(**pin_data)
        for name, pin_data in data.get("motor_pins", {}).items()
    }
    return AgentConfig(
        robot_name=data.get("robot_name", "K2Aley GAR-BOT"),
        hardware_enabled=bool(data.get("hardware_enabled", False)),
        max_speed=float(data.get("max_speed", 0.45)),
        turn_speed=float(data.get("turn_speed", 0.35)),
        command_timeout_s=float(data.get("command_timeout_s", 1.5)),
        http_host=data.get("http_host", "0.0.0.0"),
        http_port=int(data.get("http_port", 8080)),
        left_claw_device=data.get("left_claw_device", "/dev/ttyACM0"),
        right_claw_device=data.get("right_claw_device", "/dev/ttyACM1"),
        lora_device=data.get("lora_device", "/dev/serial0"),
        lora_baud=int(data.get("lora_baud", 115200)),
        ollama_enabled=bool(data.get("ollama_enabled", False)),
        ollama_url=data.get("ollama_url", "http://127.0.0.1:11434/api/generate"),
        ollama_model=data.get("ollama_model", "llama3.2:1b"),
        motor_pins=pins,
    )
