"""真实 wheel 的坏入口/修复入口对照：只操作临时副本。"""
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import venv


def run(arguments, cwd, expect=0):
    result = subprocess.run(arguments, cwd=cwd, capture_output=True, text=True,
                            timeout=90, encoding="utf-8", errors="replace")
    if expect == 0:
        assert result.returncode == 0, result.stdout + result.stderr
    else:
        assert result.returncode != 0, "broken artifact unexpectedly worked"
    return result


def main():
    source = Path(__file__).with_name("14_project")
    with tempfile.TemporaryDirectory() as directory:
        work = Path(directory)
        project = work / "project"
        shutil.copytree(source, project, ignore=shutil.ignore_patterns("build", "*.egg-info", "__pycache__"))
        original = (project / "pyproject.toml").read_text(encoding="utf-8")
        for label, config in [("bad", original.replace("series_logcount.cli:main", "series_logcount.missing:main")),
                              ("good", original)]:
            (project / "pyproject.toml").write_text(config, encoding="utf-8")
            wheels = work / f"wheels-{label}"
            # 实验刻意关闭构建隔离，调用环境须已安装固定 setuptools。
            run([sys.executable, "-m", "pip", "--disable-pip-version-check", "wheel", "--no-index", "--no-build-isolation", "--no-deps",
                 "--wheel-dir", str(wheels), str(project)], work)
            environment = work / f"venv-{label}"
            venv.EnvBuilder(with_pip=True).create(environment)
            scripts = environment / ("Scripts" if sys.platform == "win32" else "bin")
            python = scripts / ("python.exe" if sys.platform == "win32" else "python")
            run([str(python), "-m", "pip", "--disable-pip-version-check", "install", "--no-index", str(next(wheels.glob("*.whl")))], work)
            command = scripts / ("series-logcount.exe" if sys.platform == "win32" else "series-logcount")
            log = work / "sample.log"
            log.write_text("ERROR broken\nINFO ready\n", encoding="utf-8")
            result = run([str(command), str(log)], work, expect=1 if label == "bad" else 0)
            if label == "bad":
                assert "ModuleNotFoundError" in result.stderr
            else:
                assert '"ERROR": 1' in result.stdout
                location = run([str(python), "-c", "import series_logcount; print(series_logcount.__file__)"], work)
                assert "site-packages" in location.stdout
            print(label, "wheel installation succeeds; entry exit:", result.returncode)


if __name__ == "__main__":
    main()
