"""Lokální přepínač pracovních prostorů – nic neodesílá, nic neinstaluje."""

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any


def load_config(config_path: Path) -> dict[str, Any]:
    """Načte a ověří spaces_config.json."""
    if not config_path.exists():
        raise SystemExit(f"Chyba: Konfigurační soubor nenalezen: {config_path}")
    try:
        with config_path.open("r", encoding="utf-8") as f:
            return json.load(f)
    except json.JSONDecodeError as e:
        raise SystemExit(f"Chyba: Neplatný JSON v {config_path}: {e}")


def find_space(
    config: dict[str, Any],
    name: str | None,
    index: int | None
) -> dict[str, Any] | None:
    """Najde prostor podle názvu (case-insensitive) nebo indexu."""
    spaces = config.get("spaces", [])
    if index is not None:
        if 0 <= index < len(spaces):
            return spaces[index]
        return None
    if name is not None:
        name_lower = name.lower()
        for space in spaces:
            if space["name"].lower() == name_lower:
                return space
    return None


def print_space_list(spaces: list[dict[str, Any]]) -> None:
    """Vypíše seznam prostorů s indexy a stručnými instrukcemi."""
    for i, space in enumerate(spaces):
        instr = space["instructions"]
        short = instr[:80] + ("…" if len(instr) > 80 else "")
        print(f"  [{i}] {space['name']}: {short}")


def print_space_details(
    space: dict[str, Any],
    agents_def: dict[str, Any]
) -> None:
    """Vypíše detaily vybraného prostoru včetně agentů."""
    print(f"\n=== {space['name']} ===")
    print(f"Instrukce: {space['instructions']}")
    print(f"Agenti: {', '.join(space['agents'])}")

    for agent_name in space["agents"]:
        if agent_name in agents_def:
            agent = agents_def[agent_name]
            print(f"\n--- Agent: {agent_name} ---")
            print(f"Role: {agent.get('role', 'Nedefinováno')}")
            print("Schopnosti:")
            for cap in agent.get("capabilities", []):
                print(f"  - {cap}")
            print("Omezení:")
            for res in agent.get("restrictions", []):
                print(f"  - {res}")


def main() -> int:
    script_dir = Path(__file__).parent
    config_path = script_dir / "spaces_config.json"

    parser = argparse.ArgumentParser(
        description="Přepínač pracovních prostorů CyberBrain26"
    )
    parser.add_argument(
        "space_name",
        nargs="?",
        help="Název prostoru (case-insensitive)"
    )
    parser.add_argument(
        "--index",
        type=int,
        help="Index prostoru (od 0)"
    )
    parser.add_argument(
        "--list",
        action="store_true",
        help="Vypíše celou strukturu configu jako JSON"
    )
    parser.add_argument(
        "--child",
        nargs=argparse.REMAINDER,
        help="Spustí příkaz s nastavenou CYBERBRAIN_SPACE"
    )
    args = parser.parse_args()

    config = load_config(config_path)
    spaces = config.get("spaces", [])
    agents_def = config.get("agents", {})

    if args.list:
        json.dump(config, sys.stdout, ensure_ascii=False, indent=2)
        print()
        return 0

    if args.space_name is None and args.index is None:
        print("Dostupné prostory:")
        print_space_list(spaces)
        return 0

    space = find_space(config, args.space_name, args.index)
    if space is None:
        print("Neznámý prostor. Dostupné:")
        print_space_list(spaces)
        return 2

    space_name = space["name"]
    print(f'export CYBERBRAIN_SPACE="{space_name}"')

    print_space_details(space, agents_def)

    if args.child:
        cmd = args.child
        env = {**os.environ, "CYBERBRAIN_SPACE": space_name}
        try:
            result = subprocess.run(cmd, env=env, check=False)
            return result.returncode
        except FileNotFoundError:
            print(f"Chyba: Příkaz nenalezen: {cmd[0]}", file=sys.stderr)
            return 127
        except OSError as e:
            print(f"Chyba při spouštění: {e}", file=sys.stderr)
            return 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
