from __future__ import annotations

import sys
import tomllib
from pathlib import Path


ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts"))

from set_version import extract_project_version, set_project_version_in_text, write_project_version


def test_extract_project_version_reads_project_version() -> None:
    pyproject_text = (
        "[build-system]\n"
        'requires = ["setuptools>=69", "wheel"]\n\n'
        "[project]\n"
        'name = "ebay-rest-client"\n'
        'version = "0.1.0"\n'
    )

    assert extract_project_version(pyproject_text) == "0.1.0"


def test_set_project_version_in_text_updates_project_version_only() -> None:
    pyproject_text = (
        "[build-system]\n"
        'requires = ["setuptools>=69", "wheel"]\n\n'
        "[project]\n"
        'name = "ebay-rest-client"\n'
        'version = "0.1.0"\n'
        'description = "test package"\n'
    )

    updated_text = set_project_version_in_text(pyproject_text, "1.2.3")

    assert extract_project_version(updated_text) == "1.2.3"
    assert tomllib.loads(updated_text)["project"]["version"] == "1.2.3"


def test_write_project_version_updates_file(tmp_path: Path) -> None:
    pyproject_path = tmp_path / "pyproject.toml"
    pyproject_path.write_text(
        "[project]\n"
        'name = "ebay-rest-client"\n'
        'version = "0.1.0"\n',
        encoding="utf-8",
    )

    previous_version, updated_version = write_project_version(pyproject_path, "2.0.0")

    assert previous_version == "0.1.0"
    assert updated_version == "2.0.0"
    assert tomllib.loads(pyproject_path.read_text(encoding="utf-8"))["project"]["version"] == "2.0.0"