from __future__ import annotations

import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest


ROOT = Path(__file__).resolve().parents[1]
BUILD_SCRIPT = ROOT / "scripts" / "build_distribution.py"
SMOKE_SCRIPT = ROOT / "scripts" / "smoke_installed_package.py"
PRESET = ROOT / "fixtures" / "presets" / "v2-sample.json"


class DistributionTests(unittest.TestCase):
    def test_builds_wheel_and_sdist_and_runs_installed_cli(self) -> None:
        with tempfile.TemporaryDirectory() as tmp_dir:
            temp_root = Path(tmp_dir)
            dist_dir = temp_root / "dist"

            build_completed = subprocess.run(
                [sys.executable, str(BUILD_SCRIPT), "--out-dir", str(dist_dir), "--json"],
                cwd=ROOT,
                capture_output=True,
                text=True,
            )
            self.assertEqual(build_completed.returncode, 0, build_completed.stderr)

            payload = json.loads(build_completed.stdout)
            wheel_path = Path(payload["wheel"])
            sdist_path = Path(payload["sdist"])
            self.assertTrue(wheel_path.exists(), wheel_path)
            self.assertTrue(sdist_path.exists(), sdist_path)

            smoke_completed = subprocess.run(
                [
                    sys.executable,
                    str(SMOKE_SCRIPT),
                    "--wheel",
                    str(wheel_path),
                    "--preset",
                    str(PRESET),
                ],
                cwd=ROOT,
                capture_output=True,
                text=True,
            )
            self.assertEqual(smoke_completed.returncode, 0, smoke_completed.stderr)


if __name__ == "__main__":
    unittest.main()
