"""Tests for scripts/sign_release.py's production key handling.

These invoke the script as a real subprocess (it's a standalone CLI tool, not
an importable module) with a scrubbed environment so no ambient
RELEASE_PRIVATE_KEY* leaks in from the test runner's shell.

Requires `python3`/`python` and `openssl` on PATH; skipped otherwise (e.g. on
a bare Windows dev box with no Python interpreter registered).
"""
from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path

import pytest

SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts"
SIGN_SCRIPT = SCRIPTS_DIR / "sign_release.py"

requires_openssl = pytest.mark.skipif(
    shutil.which("openssl") is None, reason="openssl not available on PATH"
)


def _clean_env() -> dict:
    env = os.environ.copy()
    for key in ("RELEASE_PRIVATE_KEY", "RELEASE_PRIVATE_KEY_FILE", "WOLFPANEL_PRIVATE_KEY_PATH"):
        env.pop(key, None)
    return env


def test_sign_release_fails_without_key(tmp_path):
    target = tmp_path / "artifact.tar.gz"
    target.write_bytes(b"dummy release content")

    result = subprocess.run(
        [sys.executable, str(SIGN_SCRIPT), str(target)],
        cwd=str(tmp_path),  # no stray deploy/private_key.pem can be found here
        env=_clean_env(),
        capture_output=True,
        text=True,
    )
    assert result.returncode != 0
    assert "no production signing key configured" in result.stderr
    assert result.stdout.strip() == ""


@requires_openssl
def test_sign_release_succeeds_with_key_file(tmp_path):
    key_path = tmp_path / "test_signing_key.pem"
    subprocess.run(["openssl", "genrsa", "-out", str(key_path), "2048"], check=True, capture_output=True)

    target = tmp_path / "artifact.tar.gz"
    target.write_bytes(b"dummy release content")

    env = _clean_env()
    env["RELEASE_PRIVATE_KEY_FILE"] = str(key_path)

    result = subprocess.run(
        [sys.executable, str(SIGN_SCRIPT), str(target)],
        cwd=str(tmp_path),
        env=env,
        capture_output=True,
        text=True,
    )
    assert result.returncode == 0, result.stderr
    sig_hex = result.stdout.strip()
    assert len(sig_hex) == 512  # 256-byte RSA-2048 signature, hex-encoded
    int(sig_hex, 16)  # must be valid hex


@requires_openssl
def test_sign_release_succeeds_with_key_content_env_var(tmp_path):
    key_path = tmp_path / "test_signing_key.pem"
    subprocess.run(["openssl", "genrsa", "-out", str(key_path), "2048"], check=True, capture_output=True)

    target = tmp_path / "artifact.tar.gz"
    target.write_bytes(b"dummy release content")

    env = _clean_env()
    env["RELEASE_PRIVATE_KEY"] = key_path.read_text(encoding="utf-8")

    result = subprocess.run(
        [sys.executable, str(SIGN_SCRIPT), str(target)],
        cwd=str(tmp_path),
        env=env,
        capture_output=True,
        text=True,
    )
    assert result.returncode == 0, result.stderr
    assert len(result.stdout.strip()) == 512
