"""Registry for loaded Mira packages."""

from __future__ import annotations

from dataclasses import dataclass
import zipfile
from typing import Dict, List, Optional


@dataclass
class MiraPackageInfo:
    """Information about a loaded .mira package."""

    name: str
    version: str
    zip_file: zipfile.ZipFile
    manifest: dict
    temp_dir: str | None
    temp_zip_path: str | None
    include: str
    files: set[str]


class MiraRegistry:
    """Singleton registry for loaded .mira packages."""

    _instance: "MiraRegistry | None" = None

    def __new__(cls) -> "MiraRegistry":
        """Return the singleton instance, creating it on first use."""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._packages = {}
        return cls._instance

    def register(self, info: MiraPackageInfo) -> None:
        """Register a loaded package.

        Raises:
            RuntimeError: If the package is already registered.
        """
        if info.name in self._packages:
            raise RuntimeError(f"Package already loaded: {info.name}")
        self._packages[info.name] = info

    def unregister(self, name: str) -> MiraPackageInfo:
        """Unregister and return a package.

        Raises:
            KeyError: If the package is not registered.
        """
        return self._packages.pop(name)

    def get(self, name: str) -> MiraPackageInfo | None:
        """Get a package by name."""
        return self._packages.get(name)

    def list_all(self) -> list[MiraPackageInfo]:
        """Return all registered packages."""
        return list(self._packages.values())

    def is_loaded(self, name: str) -> bool:
        """Check whether a package is loaded."""
        return name in self._packages
