"""
AI-LSC — Registry manager.

Load / merge / query the on-disk ecosystem registry.  On first run the
default registry is written to ``<base_dir>/registry/ecosystem.json``;
on subsequent runs any *new* keys from ``DEFAULT_REGISTRY`` are merged
in so the registry auto-evolves across releases without user action.

All path operations use ``pathlib.Path`` instead of ``os.path``.
"""

from __future__ import annotations

import json
from itertools import chain
from pathlib import Path
from typing import Any

import logging

from ai_lsc.registry.defaults import DEFAULT_REGISTRY

logger = logging.getLogger(__name__)


class RegistryManager:
    """Knowledge-graph engine backed by a JSON file on disk.

    Parameters
    ----------
    registry_dir:
        Absolute path to the directory containing ``ecosystem.json``.
    """

    def __init__(self, registry_dir: str | Path) -> None:
        self.registry_dir = Path(registry_dir)
        self.registry_file: Path = self.registry_dir / "ecosystem.json"
        self.data: dict[str, dict[str, Any]] = {}
        self._bootstrap()

    # ── Bootstrap / merge ────────────────────────────────────────────

    def _bootstrap(self) -> None:
        self.registry_dir.mkdir(parents=True, exist_ok=True)
        if not self.registry_file.exists():
            self.registry_file.write_text(
                json.dumps(DEFAULT_REGISTRY, indent=4), encoding="utf-8"
            )
        try:
            self.data = json.loads(
                self.registry_file.read_text(encoding="utf-8")
            )
        except (json.JSONDecodeError, OSError) as exc:
            logger.error(
                "Failed to parse %s: %s -- re-creating from defaults",
                self.registry_file, exc,
            )
            self.data = dict(DEFAULT_REGISTRY)
            self.registry_file.write_text(
                json.dumps(self.data, indent=4), encoding="utf-8",
            )
        self._merge_with_defaults()

    def _merge_with_defaults(self) -> None:
        new_keys = {
            k: v for k, v in DEFAULT_REGISTRY.items()
            if k not in self.data
        }
        if not new_keys:
            return
        self.data.update(new_keys)
        self.registry_file.write_text(
            json.dumps(self.data, indent=4), encoding="utf-8"
        )

    # ── Queries ──────────────────────────────────────────────────────

    def get_all_tools(self) -> dict[str, dict[str, Any]]:
        """Return the full registry dict."""
        return self.data

    def get_tool(self, tool_id: str) -> dict[str, Any]:
        """Return a single tool's raw dict, or ``{}`` if unknown."""
        return self.data.get(tool_id, {})

    def get_grouped_by_layer(self) -> dict[str, list[tuple[str, dict]]]:
        """Return tools grouped and sorted by their ``layer`` field."""
        layers: dict[str, list[tuple[str, dict]]] = {}
        for t_id, meta in self.data.items():
            layers.setdefault(
                meta.get("layer", "Uncategorized"), []
            ).append((t_id, meta))
        return dict(sorted(layers.items()))

    def check_dependencies(
        self, selected: list[str],
    ) -> list[str]:
        """Return tool IDs that are required but missing from *selected*."""
        all_deps = list(chain.from_iterable(
            self.get_tool(t).get("deps", [])
            for t in selected
            if not t.startswith("skill:")
        ))
        return list({d for d in all_deps if d not in selected})
