"""服务器配置持久化管理"""
import json
import os
import uuid
from dataclasses import dataclass, field, asdict
from typing import Optional


CONFIG_DIR = os.path.join(os.path.expanduser("~"), ".sshmcp")
CONFIG_FILE = os.path.join(CONFIG_DIR, "servers.json")
ACTIVE_FILE = os.path.join(CONFIG_DIR, "active_server.json")


@dataclass
class ServerConfig:
    id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
    name: str = ""
    host: str = ""
    port: int = 22
    username: str = ""
    auth_type: str = "password"  # "password" or "key"
    password: str = ""
    key_path: str = ""
    key_passphrase: str = ""

    def to_dict(self) -> dict:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict) -> "ServerConfig":
        return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})


class ConfigManager:
    def __init__(self):
        self.servers: list[ServerConfig] = []
        self._ensure_config_dir()
        self.load()

    def _ensure_config_dir(self):
        os.makedirs(CONFIG_DIR, exist_ok=True)

    def load(self):
        if os.path.exists(CONFIG_FILE):
            try:
                with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                    data = json.load(f)
                self.servers = [ServerConfig.from_dict(s) for s in data.get("servers", [])]
            except (json.JSONDecodeError, KeyError):
                self.servers = []
        else:
            self.servers = []

    def save(self):
        data = {"servers": [s.to_dict() for s in self.servers]}
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

    def add_server(self, server: ServerConfig) -> ServerConfig:
        self.servers.append(server)
        self.save()
        return server

    def update_server(self, server_id: str, **kwargs) -> Optional[ServerConfig]:
        for s in self.servers:
            if s.id == server_id:
                for k, v in kwargs.items():
                    if hasattr(s, k):
                        setattr(s, k, v)
                self.save()
                return s
        return None

    def delete_server(self, server_id: str) -> bool:
        before = len(self.servers)
        self.servers = [s for s in self.servers if s.id != server_id]
        if len(self.servers) < before:
            self.save()
            return True
        return False

    def get_server(self, server_id: str) -> Optional[ServerConfig]:
        for s in self.servers:
            if s.id == server_id:
                return s
        return None

    def get_server_by_name(self, name: str) -> Optional[ServerConfig]:
        for s in self.servers:
            if s.name == name:
                return s
        return None

    def set_active_server(self, server_id: str):
        with open(ACTIVE_FILE, "w", encoding="utf-8") as f:
            json.dump({"active_server_id": server_id}, f)

    def get_active_server_id(self) -> Optional[str]:
        if os.path.exists(ACTIVE_FILE):
            try:
                with open(ACTIVE_FILE, "r", encoding="utf-8") as f:
                    return json.load(f).get("active_server_id")
            except (json.JSONDecodeError, KeyError):
                pass
        return None

    def get_active_server(self) -> Optional[ServerConfig]:
        sid = self.get_active_server_id()
        return self.get_server(sid) if sid else None
