"""Library facade for managing Mira packages."""

from __future__ import annotations

from typing import Any

from mira.library.installer import MiraInstaller
from mira.library.repository import MiraRepository
from mira.library.resolver import PackageResolver


class MiraLibrary:
    """High-level API for managing .mira packages."""

    def __init__(
        self,
        repository: MiraRepository | None = None,
        resolver: PackageResolver | None = None,
        installer: MiraInstaller | None = None,
    ) -> None:
        """Create a library facade.

        Args:
            repository: Optional repository instance.
            resolver: Optional resolver instance.
            installer: Optional installer instance.
        """
        self.repository = repository or MiraRepository()
        self.resolver = resolver or PackageResolver()
        self.installer = installer or MiraInstaller(
            repository=self.repository, resolver=self.resolver
        )

    def install(
        self, mira_path: str, target_dir: str | None = None, key: str | None = None
    ) -> str:
        """Install a .mira package into the repository.

        Args:
            mira_path: Path to the .mira file.
            target_dir: Optional custom repository directory.
            key: Optional encryption key for protected archives.
        """
        return self.installer.install(mira_path, target_dir=target_dir, key=key)

    def uninstall(self, name: str, key: str | None = None) -> list[str]:
        """Uninstall a package by name.

        Args:
            name: Package name.
            key: Optional encryption key for protected archives.
        """
        removed = self.repository.uninstall(name, key=key)
        for path in removed:
            print(f"Removed {path}")
        return removed

    def list(self, key: str | None = None) -> list[dict[str, Any]]:
        """List installed packages.

        Args:
            key: Optional encryption key for protected archives.
        """
        return self.repository.list_packages(key=key)

    def info(self, name: str, key: str | None = None) -> dict:
        """Get manifest information for a package by name.

        Args:
            name: Package name.
            key: Optional encryption key for protected archives.
        """
        path = self.repository.get_package_path(name, key=key)
        return self.resolver.read_manifest(path, key=key)

    def search(self, query: str, key: str | None = None) -> list[dict[str, Any]]:
        """Search installed packages by name substring.

        Args:
            query: Query substring.
            key: Optional encryption key for protected archives.
        """
        results: list[dict[str, Any]] = []
        for manifest in self.repository.list_packages(key=key):
            name = str(manifest.get("name", ""))
            if query.lower() in name.lower():
                results.append(manifest)
        return results
