# -*- coding: utf-8 -*-
"""Local registry of known MCP configs in ~/.mcp-sync/."""
import json
from pathlib import Path
from typing import Any, Dict, List, Optional


def get_registry_dir() -> Path:
    """Get or create the registry directory."""
    d = Path.home() / ".mcp-sync"
    d.mkdir(parents=True, exist_ok=True)
    return d


def get_registry_file() -> Path:
    """Get path to registry index file."""
    return get_registry_dir() / "registry.json"


def load_registry() -> Dict[str, Any]:
    """Load the registry index. Returns empty dict if not exists."""
    f = get_registry_file()
    if not f.exists():
        return {"configs": {}}
    return json.loads(f.read_text(encoding="utf-8"))


def save_registry(registry: Dict[str, Any]) -> None:
    """Save registry index to disk."""
    f = get_registry_file()
    f.write_text(json.dumps(registry, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def register_config(path: str | Path, name: Optional[str] = None) -> str:
    """Register a config file. Returns the alias used."""
    p = Path(path).resolve()
    if not p.exists():
        raise FileNotFoundError(f"Config not found: {p}")

    alias = name or p.parent.name
    registry = load_registry()
    registry["configs"][alias] = {
        "path": str(p),
        "registered": True,
    }
    save_registry(registry)
    return alias


def unregister_config(name: str) -> bool:
    """Remove a config from the registry."""
    registry = load_registry()
    if name in registry.get("configs", {}):
        del registry["configs"][name]
        save_registry(registry)
        return True
    return False


def list_registered() -> List[Dict[str, str]]:
    """List all registered configs."""
    registry = load_registry()
    result = []
    for alias, info in registry.get("configs", {}).items():
        path = info.get("path", "?")
        exists = Path(path).exists()
        result.append({
            "name": alias,
            "path": path,
            "exists": "yes" if exists else "MISSING",
        })
    return result
