import textwrap
from pathlib import Path
from textwrap import dedent

from pytest import MonkeyPatch

from hatch_gradle_version.common.gradle import GradleVersion

from .json import JSONVersionSource


def test_json_version(tmp_path: Path, monkeypatch: MonkeyPatch):
    # arrange
    monkeypatch.setenv("HATCH_GRADLE_DIR", "gradle_dir")

    json = tmp_path / "gradle_dir" / "mod.json"
    json.parent.mkdir()
    json.write_text(
        dedent(
            """
            {
                "core": {
                    "name": "hexbound",
                    "version": "0.1.4+1.19.2",
                    "repository": "https://github.com/Cypher121/hexbound/"
                },
                "platforms": {
                    "modrinth": {
                        "id": "PHgo4bVw"
                    },
                    "curseforge": {
                        "id": "739791"
                    }
                },
                "foo": [
                    "bar",
                    "baz",
                    {
                        "qux": "quux"
                    }
                ]
            }
            """
        )
    )

    (tmp_path / "__version__.py").write_text('PY_VERSION = "1.0"')

    hook = JSONVersionSource.from_config(
        tmp_path.as_posix(),
        {
            "source": "json",
            "py-path": "__version__.py",
            "json-path": "mod.json",
            "key": "core.version",
        },
    )

    gradle_version = hook.get_gradle_version()

    assert gradle_version == GradleVersion(
        raw_version="0.1.4+1.19.2",
        version="0.1.4",
        rc=None,
        build="1.19.2",
        extra_versions={
            "core.name": "hexbound",
            "core.version": "0.1.4+1.19.2",
            "core.repository": "https://github.com/Cypher121/hexbound/",
            "platforms.modrinth.id": "PHgo4bVw",
            "platforms.curseforge.id": "739791",
            "foo.0": "bar",
            "foo.1": "baz",
            "foo.2.qux": "quux",
        },
    )

    hook.get_version_data()

    generated_version_file = (tmp_path / "__gradle_version__.py").read_text("utf-8")
    assert generated_version_file == textwrap.dedent(
        """\
        # This file is auto-generated by hatch-gradle-version. Do not edit.

        GRADLE_VERSION = "0.1.4+1.19.2"
        FULL_VERSION = "0.1.4.1.0"

        CORE_NAME = "hexbound"
        CORE_REPOSITORY = "https://github.com/Cypher121/hexbound/"
        CORE_VERSION = "0.1.4+1.19.2"
        FOO_0 = "bar"
        FOO_1 = "baz"
        FOO_2_QUX = "quux"
        PLATFORMS_CURSEFORGE_ID = "739791"
        PLATFORMS_MODRINTH_ID = "PHgo4bVw"
        """
    )
