"""Tests for the Mira library management."""

from __future__ import annotations

import os
from mira.builder.builder import MiraBuilder
from mira.library.library import MiraLibrary
from mira.library.repository import MiraRepository
from tests.helpers import temporary_directory


def _create_project(base_dir: str) -> str:
    project_dir = os.path.join(base_dir, "sample_project")
    os.makedirs(project_dir, exist_ok=True)

    pyproject = """
[project]
name = "my_engine"
version = "1.0.0"
description = "My awesome engine"
dependencies = []

[tool.mira]
include = "engine"
""".strip()

    with open(os.path.join(project_dir, "pyproject.toml"), "w", encoding="utf-8") as handle:
        handle.write(pyproject)

    engine_dir = os.path.join(project_dir, "engine")
    os.makedirs(engine_dir, exist_ok=True)

    with open(os.path.join(engine_dir, "__init__.py"), "w", encoding="utf-8") as handle:
        handle.write("VALUE = 1\n")

    return project_dir


def test_library_install_list_uninstall() -> None:
    with temporary_directory() as tmp:
        project_dir = _create_project(tmp)
        builder = MiraBuilder(project_dir, output_dir="dist")
        mira_path = builder.build()

        repo_dir = os.path.join(tmp, "repo")
        library = MiraLibrary(repository=MiraRepository(base_dir=repo_dir))

        library.install(mira_path)
        packages = library.list()
        assert packages
        assert packages[0]["name"] == "my_engine"

        info = library.info("my_engine")
        assert info["version"] == "1.0.0"

        library.uninstall("my_engine")
        assert library.list() == []
