"""Configuration management for Agent Duel CLI."""

import json
import os
from pathlib import Path
from typing import Optional

# Default server URLs
DEFAULT_API_URL = "http://localhost:8000/api"
DEFAULT_WS_URL = "ws://localhost:8000/ws"


def get_config_dir() -> Path:
    """Get the config directory, respecting AGENTDUEL_CONFIG_DIR env var."""
    env_dir = os.environ.get("AGENTDUEL_CONFIG_DIR")
    if env_dir:
        return Path(env_dir)
    return Path.home() / ".agentduel"


def get_config_file() -> Path:
    """Get the config file path."""
    return get_config_dir() / "config.json"


def ensure_config_dir():
    """Ensure the config directory exists."""
    get_config_dir().mkdir(parents=True, exist_ok=True)


def load_config() -> dict:
    """Load configuration from file."""
    ensure_config_dir()
    config_file = get_config_file()
    if config_file.exists():
        try:
            with open(config_file) as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return {}
    return {}


def save_config(config: dict):
    """Save configuration to file."""
    ensure_config_dir()
    config_file = get_config_file()
    with open(config_file, "w") as f:
        json.dump(config, f, indent=2)


def get_token() -> Optional[str]:
    """Get the stored auth token."""
    config = load_config()
    return config.get("token")


def set_token(token: str):
    """Store the auth token."""
    config = load_config()
    config["token"] = token
    save_config(config)


def clear_token():
    """Clear the stored auth token."""
    config = load_config()
    config.pop("token", None)
    save_config(config)


def get_active_agent() -> Optional[str]:
    """Get the stored active agent file path."""
    config = load_config()
    return config.get("active_agent")


def set_active_agent(path: str):
    """Store the active agent file path."""
    config = load_config()
    config["active_agent"] = path
    save_config(config)


def clear_active_agent():
    """Clear the stored active agent path."""
    config = load_config()
    config.pop("active_agent", None)
    save_config(config)


def get_api_url() -> str:
    """Get the API base URL."""
    return os.environ.get("AGENTDUEL_API_URL", DEFAULT_API_URL)


def get_ws_url() -> str:
    """Get the WebSocket base URL."""
    return os.environ.get("AGENTDUEL_WS_URL", DEFAULT_WS_URL)
