from __future__ import annotations

import os
import shutil
import subprocess
import zipfile
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parents[1]
BUILD_SCRIPT = REPO_ROOT / "scripts" / "reproducible-wheel-build"
EXPECTED_ZIP_TIMESTAMP = (2000, 1, 1, 0, 0, 0)


@pytest.mark.integration
def test_copied_source_wheels_are_byte_reproducible(tmp_path: Path) -> None:
    source = tmp_path / "source"
    package = source / "repro_fixture"
    package.mkdir(parents=True)
    (source / "pyproject.toml").write_text(
        """[build-system]
requires = ["setuptools>=77.0,<83"]
build-backend = "setuptools.build_meta"

[project]
name = "repro-fixture"
version = "1.0.0"
"""
    )
    (package / "__init__.py").write_text('VALUE = "stable"\n')

    wheels: list[Path] = []
    for index, timestamp in enumerate((1_700_000_000, 1_800_000_000)):
        copied_source = tmp_path / f"copy-{index}"
        shutil.copytree(source, copied_source)
        for path in copied_source.rglob("*"):
            os.utime(path, (timestamp, timestamp))

        output = tmp_path / f"dist-{index}"
        build = subprocess.run(
            [str(BUILD_SCRIPT), str(copied_source), str(output)],
            cwd=tmp_path,
            capture_output=True,
            text=True,
            timeout=240,
        )
        assert build.returncode == 0, build.stderr
        built = list(output.glob("*.whl"))
        assert len(built) == 1
        wheels.append(built[0])

    assert wheels[0].read_bytes() == wheels[1].read_bytes()
    with zipfile.ZipFile(wheels[0]) as archive:
        assert {member.date_time for member in archive.infolist()} == {EXPECTED_ZIP_TIMESTAMP}
