"""Packaging metadata and tooling tests."""

from __future__ import annotations

import json
from pathlib import Path

import sys

try:
    import tomllib as toml_loader
except ModuleNotFoundError:  # pragma: no cover
    import tomli as toml_loader


PYPROJECT = Path("pyproject.toml")


def test_pyproject_metadata() -> None:
    data = toml_loader.loads(PYPROJECT.read_text(encoding="utf-8"))
    project = data.get("project", {})
    assert project.get("name") == "aurora-se"
    version = project.get("version")
    assert version and version.count(".") >= 2, "Version must be semver-like"
    scripts = project.get("scripts", {})
    assert "aurora-se" in scripts


def test_packaging_scripts_exist(tmp_path: Path) -> None:
    scripts_dir = Path("scripts")
    expected = [
        scripts_dir / "build_package.sh",
        scripts_dir / "build_package.ps1",
        scripts_dir / "generate_checksums.py",
    ]
    for script in expected:
        assert script.exists(), f"Missing packaging script {script}"

    checksum_output = tmp_path / "dist"
    checksum_output.mkdir()
    artifact = checksum_output / "demo-0.0.1.whl"
    artifact.write_bytes(b"demo")
    import importlib.util

    spec = importlib.util.spec_from_file_location("checksum", scripts_dir / "generate_checksums.py")
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)  # type: ignore[attr-defined]
    module.main(checksum_output)
    sums = (checksum_output / "SHA256SUMS").read_text(encoding="utf-8")
    assert "demo-0.0.1.whl" in sums


def test_node_wrapper_metadata() -> None:
    package_json = Path("node/aurora-se-cli/package.json")
    assert package_json.exists()
    metadata = json.loads(package_json.read_text(encoding="utf-8"))
    assert metadata["name"] == "aurora-se-cli"
    assert "aurora-se-cli" in metadata["bin"]

