"""Tests for the release automation helpers."""

import importlib.util
import sys
from pathlib import Path


def _load_release_module():
    spec = importlib.util.spec_from_file_location("release_script", Path("scripts/release.py"))
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


def test_prompt_credentials_accepts_token_as_username(monkeypatch):
    release = _load_release_module()
    monkeypatch.delenv("TWINE_USERNAME", raising=False)
    monkeypatch.delenv("TWINE_PASSWORD", raising=False)
    monkeypatch.delenv("soigia-pip-user", raising=False)
    monkeypatch.delenv("soigia-pip-password", raising=False)
    monkeypatch.setattr("builtins.input", lambda prompt: "pypi-abc123")
    called = {}

    def fail_getpass(prompt):
        called["getpass"] = True
        return "should-not-run"

    monkeypatch.setattr(release.getpass, "getpass", fail_getpass)

    user, password = release._prompt_credentials("PyPI")

    assert user == "__token__"
    assert password == "pypi-abc123"
    assert "getpass" not in called


def test_prompt_credentials_accepts_token_in_environment(monkeypatch):
    release = _load_release_module()
    monkeypatch.setattr("builtins.input", lambda prompt: "someone")
    monkeypatch.setattr(release.getpass, "getpass", lambda prompt: "pypi-envtoken")
    user, password = release._prompt_credentials("PyPI")

    assert user == "__token__"
    assert password == "pypi-envtoken"


def test_build_upload_command_uses_repository_alias_by_default():
    release = _load_release_module()

    command = release._build_upload_command(["dist/a.whl"])

    assert command[:5] == [sys.executable, "-m", "twine", "upload", "--non-interactive"]
    assert "-r" in command
    assert "soigia" in command
    assert "--repository-url" not in command


def test_build_upload_command_uses_repository_url_when_provided():
    release = _load_release_module()

    command = release._build_upload_command(
        ["dist/a.whl"],
        repository="soigia",
        repository_url="https://test.pypi.org/legacy/",
        username="__token__",
        password="pypi-abc",
    )

    assert "--repository-url" in command
    assert "https://test.pypi.org/legacy/" in command
    assert "-r" not in command
    assert "-u" in command
    assert "-p" in command
