# flake8: noqa: F841

import os
import subprocess
from pathlib import Path
from typing import cast, override

import tomlkit
from rich.prompt import Confirm, InvalidResponse, Prompt, PromptBase

from kamuidrome.meta import AvailablePackLoader


class NonEmptyPrompt(PromptBase[str]):
    """
    A prompt that makes sure the entry is non-empty.
    """

    @override
    def process_response(self, value: str) -> str:
        if not value:
            raise InvalidResponse("[prompt.invalid]Enter a non-empty value")

        return super().process_response(value)


def interactively_create_pack(
    path: Path,
    with_git: bool,
) -> int:
    """
    Creates a new modpack interactively.
    """

    name = NonEmptyPrompt.ask("[yellow]Pack name")
    raw_minecraft_version = NonEmptyPrompt.ask("[yellow]Minecraft version")
    mc_version: tuple[int, int] = cast(
        tuple[int, int], tuple(map(int, raw_minecraft_version.split(".")[1:]))
    )
    assert len(mc_version) == 2, "enter the right version idiot!"

    version = Prompt.ask("[yellow]Pack version", default="0.1.0")

    if mc_version < (20, 0):
        loader_choices = ["legacyforge", "fabric", "quilt"]
    else:
        loader_choices = ["legacyforge", "neoforge", "fabric", "quilt"]

    loader = AvailablePackLoader(Prompt.ask("[yellow]Modloader", choices=loader_choices))
    loader_version: str | None = Prompt.ask("[yellow]Modloader version (leave empty for auto)")
    if not loader_version:
        loader_version = None

    if mc_version >= (20, 0) and loader in (
        AvailablePackLoader.LEGACY_FORGE,
        AvailablePackLoader.NEOFORGE,
    ):
        enable_sinytra = Confirm.ask("[yellow]Enable Sinytra compatibility", default=True)
    else:
        enable_sinytra = False

    if all((enable_sinytra, loader == AvailablePackLoader.LEGACY_FORGE, mc_version == (20, 1))):
        # hardcoded lol.
        loader_version = "47.1.3"

    pack_toml = tomlkit.document()
    pack_toml.add(tomlkit.comment("This pack.toml was generated by ``kamuidrome init``!"))
    pack_toml.add(tomlkit.nl())

    pack_toml.add(tomlkit.comment("Human-friendly name of the pack, used during export."))
    pack_toml["name"] = name
    pack_toml.add(tomlkit.comment("Human-friendly version of the pack, used during export."))
    pack_toml["version"] = version
    pack_toml.add(tomlkit.comment("The minecraft version for this pack."))
    pack_toml["game_version"] = raw_minecraft_version
    pack_toml.add(
        tomlkit.comment(
            "A list of additional directories to include when building a pack or "
            "generating symlinks."
        )
    )
    pack_toml["include_directories"] = []
    pack_toml.add(tomlkit.nl())

    loader_toml = tomlkit.document()
    loader_toml.add(tomlkit.comment("The type of modloader this pack runs."))
    loader_toml["type"] = loader.value

    if loader_version is not None:
        loader_toml.add(
            tomlkit.comment(
                "The loader version is normally automatically selected but it can be overridden here."  # noqa: E501
            )
        )
        loader_toml["version"] = loader_version

    loader_toml.add(
        tomlkit.comment(
            'For "legacyforge" and "neoforge", this enables using Fabric mods and treating Forgified Fabric API'  # noqa: E501
        )
    )
    loader_toml.add(tomlkit.comment("as Fabric API for dependency purposes."))
    loader_toml["sinytra_compat"] = enable_sinytra

    pack_toml["loader"] = loader_toml

    # not 100% why comments aren't preserved in the nested table, but whatever.
    with (path / "pack.toml").open(mode="w") as f:
        tomlkit.dump(pack_toml, f)  # type: ignore

    (path / "config").mkdir(exist_ok=True)
    (path / "mods").mkdir(exist_ok=True)
    (path / "mods" / "mod-index.json").write_text(r"{}" + os.linesep)

    if with_git:
        subprocess.check_call(["git", "init", str(path.resolve())])
        (path / "config" / ".gitkeep").write_text("")

    return 0
