"""配置文件管理模块

配置文件位置: ~/.config/s3c/credentials.json
格式: JSON 数组，每个元素包含一个 S3 配置
"""
import json
import os
from pathlib import Path
from typing import Optional

# 配置文件路径
CONFIG_DIR = Path.home() / ".config" / "s3c"
CREDENTIALS_FILE = CONFIG_DIR / "credentials.json"


class ClusterConfig:
    """单个 S3 集群配置"""

    def __init__(self, data: dict):
        self.name: str = data["name"]
        self.description: str = data.get("description", "")
        self.endpoint_url: str = data["endpoint_url"]
        self.access_key: str = data["access_key"]
        self.secret_key: str = data["secret_key"]
        self.region: str = data.get("region", "us-east-1")

    def to_dict(self) -> dict:
        return {
            "name": self.name,
            "description": self.description,
            "endpoint_url": self.endpoint_url,
            "access_key": self.access_key,
            "secret_key": self.secret_key,
            "region": self.region,
        }


def load_clusters() -> list[ClusterConfig]:
    """从配置文件加载所有集群配置"""
    if not CREDENTIALS_FILE.exists():
        return []

    try:
        with open(CREDENTIALS_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)

        if not isinstance(data, list):
            raise ValueError("credentials.json 必须是一个 JSON 数组")

        return [ClusterConfig(item) for item in data]
    except (json.JSONDecodeError, KeyError, ValueError) as e:
        raise RuntimeError(f"读取配置文件失败: {e}") from e


def get_cluster(name: Optional[str] = None) -> ClusterConfig:
    """获取指定名称的集群配置，未指定则返回第一个

    Args:
        name: 集群名称，None 表示使用默认（第一个）配置

    Returns:
        ClusterConfig 对象

    Raises:
        SystemExit: 配置文件不存在或找不到指定配置时退出
    """
    clusters = load_clusters()

    if not clusters:
        print(
            f"[错误] 配置文件不存在或为空: {CREDENTIALS_FILE}\n"
            f"请创建配置文件并添加至少一个 S3 配置。\n"
            f"示例格式:\n"
            f'[\n  {{"name": "default", "description": "默认配置",\n'
            f'   "endpoint_url": "https://s3.amazonaws.com",\n'
            f'   "access_key": "YOUR_KEY", "secret_key": "YOUR_SECRET",\n'
            f'   "region": "us-east-1"}}\n]'
        )
        raise SystemExit(1)

    if name is None:
        return clusters[0]

    for cluster in clusters:
        if cluster.name == name:
            return cluster

    available = ", ".join(c.name for c in clusters)
    print(f"[错误] 找不到集群配置 '{name}'，可用配置: {available}")
    raise SystemExit(1)
