from __future__ import annotations

import json
from pathlib import Path
from typing import Any


DEFAULT_AGENTS = [
    {
        "id": "echo",
        "name": "Echo local",
        "type": "echo",
        "description": "Agent de test intégré, sans modèle ni credentials.",
        "enabled": True,
    },
    {
        "id": "hermes",
        "name": "Hermes CLI",
        "type": "cli",
        "description": "Lance Hermes en mode one-shot via hermes chat -q.",
        "command": ["hermes", "chat", "-q", "{prompt}"],
        "timeout_seconds": 300,
        "enabled": True,
    },
    {
        "id": "claude-code",
        "name": "Claude Code",
        "type": "cli",
        "description": "Claude Code en mode print, prêt à l'emploi dans la GUI.",
        "command": ["claude", "-p", "--output-format", "text", "--permission-mode", "default", "{prompt}"],
        "timeout_seconds": 300,
        "enabled": True,
    },
    {
        "id": "openclaw",
        "name": "OpenClaw",
        "type": "cli",
        "description": "Exemple OpenClaw. Ajuster la commande selon ton installation.",
        "command": ["openclaw", "chat", "-q", "{prompt}"],
        "timeout_seconds": 300,
        "enabled": False,
    },
]


def load_agents(config_path: str | Path) -> list[dict[str, Any]]:
    path = Path(config_path)
    if not path.exists():
        return DEFAULT_AGENTS
    with path.open("r", encoding="utf-8") as handle:
        data = json.load(handle)
    agents = data.get("agents", data if isinstance(data, list) else [])
    if not isinstance(agents, list):
        raise ValueError("La config agents doit contenir une liste 'agents'.")
    return [agent for agent in agents if agent.get("enabled", True)]


def find_agent(agents: list[dict[str, Any]], agent_id: str) -> dict[str, Any]:
    for agent in agents:
        if agent.get("id") == agent_id:
            return agent
    raise KeyError(f"Agent inconnu: {agent_id}")
