"""Fresh-environment contract for the documented source-checkout install."""

from __future__ import annotations

import json
import os
import subprocess
from pathlib import Path

import pytest

from .conftest import _uv

ROOT = Path(__file__).resolve().parents[3]


def _run(*command: str, cwd: Path, environment: dict[str, str]) -> subprocess.CompletedProcess[str]:
    """Run one documented-install command with source imports disabled."""
    result = subprocess.run(command, cwd=cwd, env=environment, text=True, capture_output=True, check=False)
    if result.returncode:
        raise AssertionError(
            "source-checkout installation E2E command failed\n"
            f"command: {command!r}\n"
            f"cwd: {cwd}\n"
            f"stdout:\n{result.stdout}\n"
            f"stderr:\n{result.stderr}\n"
        )
    return result


@pytest.mark.e2e
@pytest.mark.parametrize(
    ("install_target", "exercise_local_golden_path"),
    ((".[torchsig,sionna]", True), (".[gemini]", False)),
    ids=("tutorial-extras", "gemini-extra"),
)
def test_fresh_editable_source_checkout_install_matches_documented_uv_command(
    tmp_path: Path, install_target: str, exercise_local_golden_path: bool
) -> None:
    """Install each documented source-checkout extra contract in a fresh venv.

    An editable install must deliberately import ``rfgen`` from this checkout's
    ``src/`` tree, unlike the installed-wheel fixture whose import is required
    to be in the temporary environment's ``site-packages`` directory.
    """
    venv = tmp_path / ".venv-rfgen"
    execution_directory = tmp_path / "outside-checkout"
    execution_directory.mkdir()
    environment = dict(os.environ)
    environment.pop("PYTHONPATH", None)
    uv = _uv()

    _run(uv, "venv", "--python", "3.11", str(venv), cwd=tmp_path, environment=environment)
    python = venv / "bin" / "python"
    rfgen = venv / "bin" / "rfgen"
    _run(
        uv,
        "pip",
        "install",
        "--python",
        str(python),
        "-e",
        install_target,
        cwd=ROOT,
        environment=environment,
    )

    observed = _run(
        str(python),
        "-c",
        "\n".join(
            (
                "import importlib.metadata",
                "import json",
                "from pathlib import Path",
                "import rfgen",
                "distribution = importlib.metadata.distribution('rfgen')",
                "direct_url = distribution.read_text('direct_url.json')",
                "assert direct_url is not None, 'editable install must record direct_url metadata'",
                "print(json.dumps({'module': str(Path(rfgen.__file__).resolve()), 'direct_url': json.loads(direct_url)}, sort_keys=True))",
            )
        ),
        cwd=execution_directory,
        environment=environment,
    )
    payload = json.loads(observed.stdout)
    assert Path(payload["module"]).is_relative_to(ROOT / "src")
    assert "site-packages" not in payload["module"]
    assert payload["direct_url"] == {"dir_info": {"editable": True}, "url": ROOT.as_uri()}

    help_result = _run(str(rfgen), "--help", cwd=execution_directory, environment=environment)
    assert "Synthetic RF" in help_result.stdout
    if exercise_local_golden_path:
        config_dir = execution_directory / "chirp-config"
        output = execution_directory / "chirp-output"
        _run(
            str(rfgen),
            "init",
            "chirp-radar",
            str(config_dir),
            cwd=execution_directory,
            environment=environment,
        )
        _run(
            str(rfgen), "generate", "--config-dir", str(config_dir), f"storage.destination=file://{output}",
            cwd=execution_directory, environment=environment,
        )
        inspected = _run(
            str(rfgen), "inspect", str(output), cwd=execution_directory, environment=environment
        )
        assert (output / "data.h5").is_file()
        assert json.loads(inspected.stdout)["report"]["record_count"] == 24
