from __future__ import annotations

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

from mrp.auth import default_key_path


@dataclass
class Config:
    relay_url: str = ""
    key_file: str | None = None
    agent_name: str | None = None
    capabilities: list[str] = field(default_factory=list)
    metadata: dict[str, str] = field(default_factory=dict)
    poll_interval: int = 0
    auto_register: bool = True
    ephemeral: bool = False


def load_config(args=None) -> Config:
    """Load config with priority: CLI args > env vars > config file > defaults."""
    config = Config()

    # 1. Config file (lowest priority)
    config_path = None
    if args and getattr(args, "config", None):
        config_path = args.config
    elif os.environ.get("MRP_CONFIG"):
        config_path = os.environ["MRP_CONFIG"]
    else:
        default_path = Path("mrp-mcp.json")
        if default_path.exists():
            config_path = str(default_path)

    if config_path:
        with open(config_path) as f:
            data = json.load(f)
        config.relay_url = data.get("relay", config.relay_url)
        config.key_file = data.get("key_file", config.key_file)
        config.agent_name = data.get("name", config.agent_name)
        config.capabilities = data.get("capabilities", config.capabilities)
        config.metadata = data.get("metadata", config.metadata)
        config.poll_interval = data.get("poll_interval", config.poll_interval)
        config.auto_register = data.get("auto_register", config.auto_register)

    # 2. Environment variables
    if os.environ.get("MRP_RELAY_URL"):
        config.relay_url = os.environ["MRP_RELAY_URL"]
    if os.environ.get("MRP_KEY_FILE"):
        config.key_file = os.environ["MRP_KEY_FILE"]
    if os.environ.get("MRP_AGENT_NAME"):
        config.agent_name = os.environ["MRP_AGENT_NAME"]
    if os.environ.get("MRP_CAPABILITIES"):
        config.capabilities = os.environ["MRP_CAPABILITIES"].split(",")
    if os.environ.get("MRP_METADATA"):
        config.metadata = json.loads(os.environ["MRP_METADATA"])
    if os.environ.get("MRP_POLL_INTERVAL"):
        config.poll_interval = int(os.environ["MRP_POLL_INTERVAL"])

    # 3. CLI args (highest priority)
    if args:
        if getattr(args, "relay", None):
            config.relay_url = args.relay
        if getattr(args, "key", None):
            config.key_file = args.key
        if getattr(args, "name", None):
            config.agent_name = args.name
        if getattr(args, "cap", None):
            config.capabilities = args.cap
        if getattr(args, "poll_interval", None) is not None:
            config.poll_interval = args.poll_interval
        if getattr(args, "ephemeral", False):
            config.ephemeral = True

    if not config.relay_url:
        raise ValueError(
            "MRP relay URL is required. Set MRP_RELAY_URL env var, "
            "pass --relay, or add 'relay' to mrp-mcp.json."
        )

    # Default to persistent identity unless --ephemeral or an explicit key was set
    if config.key_file is None and not config.ephemeral:
        config.key_file = default_key_path(config.agent_name)

    return config
