from __future__ import annotations

from pathlib import Path

import pytest

from rimpack.core.mods.mod_folder import ModFolder, ModFolderError, load_mod_folder


def test_load_mod_folder_with_about_and_load_folders() -> None:
    mod_path = Path("tests") / "__tmp_mod_with_load_folders"
    about_path = mod_path / "About" / "About.xml"
    load_folders_path = mod_path / "LoadFolders.xml"
    try:
        about_path.parent.mkdir(parents=True)
        _ = about_path.write_text(
            """\
<ModMetaData>
  <packageId>author.mod</packageId>
  <name>My Mod Name</name>
  <author>Author</author>
  <description>Description</description>
  <supportedVersions>
    <li>1.6</li>
  </supportedVersions>
</ModMetaData>
""",
            encoding="utf-8",
        )
        _ = load_folders_path.write_text(
            """\
<loadFolders>
  <v1.6>
    <li>Defs</li>
  </v1.6>
</loadFolders>
""",
            encoding="utf-8",
        )

        mod_folder = load_mod_folder(mod_path)

        assert mod_folder == ModFolder(
            path=mod_path.resolve(),
            about=mod_folder.about,
            load_folders=mod_folder.load_folders,
        )
        assert mod_folder.about.package_id == "author.mod"
        assert mod_folder.load_folders is not None
        assert mod_folder.load_folders.versions[0].entries[0].path == "Defs"
    finally:
        load_folders_path.unlink(missing_ok=True)
        about_path.unlink(missing_ok=True)
        about_path.parent.rmdir()
        mod_path.rmdir()


def test_load_mod_folder_without_load_folders() -> None:
    mod_path = Path("tests") / "__tmp_mod_without_load_folders"
    about_path = mod_path / "About" / "About.xml"
    try:
        about_path.parent.mkdir(parents=True)
        _ = about_path.write_text(
            """\
<ModMetaData>
  <packageId>author.mod</packageId>
  <name>My Mod Name</name>
  <author>Author</author>
  <description>Description</description>
  <supportedVersions>
    <li>1.6</li>
  </supportedVersions>
</ModMetaData>
""",
            encoding="utf-8",
        )

        mod_folder = load_mod_folder(mod_path)

        assert mod_folder.load_folders is None
        assert mod_folder.about.name == "My Mod Name"
    finally:
        about_path.unlink(missing_ok=True)
        about_path.parent.rmdir()
        mod_path.rmdir()


def test_reject_non_directory_path() -> None:
    file_path = Path("tests") / "__tmp_mod_file.txt"
    try:
        _ = file_path.write_text("not a directory", encoding="utf-8")

        with pytest.raises(ModFolderError, match="not a directory"):
            _ = load_mod_folder(file_path)
    finally:
        file_path.unlink(missing_ok=True)


def test_reject_missing_about_xml() -> None:
    mod_path = Path("tests") / "__tmp_mod_missing_about"
    try:
        mod_path.mkdir()

        with pytest.raises(ModFolderError, match="missing required file"):
            _ = load_mod_folder(mod_path)
    finally:
        mod_path.rmdir()
