"""Persistent AgentCore configuration at ~/.alice/agentcore.json."""

from __future__ import annotations

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

_CONFIG_DIR = Path.home() / ".alice"
_CONFIG_FILE = _CONFIG_DIR / "agentcore.json"


@dataclass
class DeploymentConfig:
    """Persisted AgentCore Runtime deployment metadata."""

    name: str
    endpoint: str | None = None
    memory_name: str | None = None
    model_id: str | None = None


@dataclass
class GatewayConfig:
    """Persisted AgentCore Gateway metadata."""

    name: str
    endpoint_url: str | None = None
    auth_config: dict[str, object] | None = None
    tools: list[str] | None = None


@dataclass
class AgentCoreConfig:
    """Top-level AgentCore configuration persisted to ~/.alice/agentcore.json."""

    deployment: DeploymentConfig | None = None
    gateway: GatewayConfig | None = None


def _is_nonblank_str(value: object) -> bool:
    return isinstance(value, str) and value.strip() != ""


def _parse_deployment(data: object) -> DeploymentConfig | None:
    if not isinstance(data, dict):
        return None
    name = data.get("name")
    if not _is_nonblank_str(name):
        return None
    return DeploymentConfig(
        name=str(name),
        endpoint=data.get("endpoint") if _is_nonblank_str(data.get("endpoint")) else None,
        memory_name=data.get("memory_name") if _is_nonblank_str(data.get("memory_name")) else None,
        model_id=data.get("model_id") if _is_nonblank_str(data.get("model_id")) else None,
    )


def _parse_gateway(data: object) -> GatewayConfig | None:
    if not isinstance(data, dict):
        return None
    name = data.get("name")
    if not _is_nonblank_str(name):
        return None
    name = str(name)
    auth_config = data.get("auth_config")
    if not isinstance(auth_config, dict):
        auth_config = None
    tools = data.get("tools")
    if not isinstance(tools, list) or not all(isinstance(t, str) for t in tools):
        tools = None
    return GatewayConfig(
        name=name,
        endpoint_url=data.get("endpoint_url")
        if _is_nonblank_str(data.get("endpoint_url"))
        else None,
        auth_config=auth_config or None,
        tools=tools or None,
    )


def load_agentcore_config() -> AgentCoreConfig:
    """Load AgentCore config from disk, returning defaults if the file is missing or corrupt."""
    if not _CONFIG_FILE.exists():
        return AgentCoreConfig()
    try:
        data = json.loads(_CONFIG_FILE.read_text())
        if not isinstance(data, dict):
            return AgentCoreConfig()
        return AgentCoreConfig(
            deployment=_parse_deployment(data.get("deployment")),
            gateway=_parse_gateway(data.get("gateway")),
        )
    except (json.JSONDecodeError, OSError):
        return AgentCoreConfig()


def save_agentcore_config(config: AgentCoreConfig) -> Path:
    """Write AgentCore config to disk with 0o600 permissions. Returns the path written."""
    _CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    os.chmod(_CONFIG_DIR, 0o700)

    payload: dict[str, object] = {}
    if config.deployment is not None:
        payload["deployment"] = asdict(config.deployment)
    if config.gateway is not None:
        payload["gateway"] = asdict(config.gateway)

    _CONFIG_FILE.write_text(json.dumps(payload, indent=2) + "\n")
    os.chmod(_CONFIG_FILE, 0o600)
    return _CONFIG_FILE


def clear_deployment_config() -> None:
    """Load config, set deployment to None, and save."""
    config = load_agentcore_config()
    config.deployment = None
    save_agentcore_config(config)


def clear_gateway_config() -> None:
    """Load config, set gateway to None, and save."""
    config = load_agentcore_config()
    config.gateway = None
    save_agentcore_config(config)
