"""External extension-wheel contracts against a fresh RFGen wheel."""

from __future__ import annotations

import json
import os
import subprocess
from pathlib import Path

import pytest

from .conftest import InstalledWheel, _uv

ROOT = Path(__file__).resolve().parents[3]
FIXTURE_ROOT = ROOT / "tests" / "integration" / "local" / "fixture_plugin"


def _build_and_install_fixture(installed_wheel: InstalledWheel, tmp_path: Path) -> Path:
    """Build the checked-in generic extension fixture and install its wheel."""
    dist = tmp_path / "fixture-dist"
    build = subprocess.run(
        (_uv(), "build", "--out-dir", str(dist)),
        cwd=FIXTURE_ROOT,
        env={key: value for key, value in os.environ.items() if key != "PYTHONPATH"},
        text=True,
        capture_output=True,
        check=False,
    )
    assert build.returncode == 0, build.stderr
    wheel = next(dist.glob("*.whl"), None)
    assert wheel is not None, build.stdout
    installed_wheel.run(
        _uv(), "pip", "install", "--python", str(installed_wheel.python), str(wheel), cwd=tmp_path
    )
    return wheel


@pytest.mark.e2e
def test_external_fixture_wheel_discovers_generic_extensions(
    installed_wheel: InstalledWheel, tmp_path: Path
) -> None:
    """An installed extension discovers its public source and transform hooks."""
    wheel = _build_and_install_fixture(installed_wheel, tmp_path)
    result = installed_wheel.run(
        str(installed_wheel.python),
        "-c",
        "\n".join(
            (
                "import json",
                "from rfgen.plugins import EntryPointRegistry",
                "from rfgen.graph import SceneRecord",
                "from rfgen.storage import get_storage, storage_names",
                "sources = EntryPointRegistry('rfgen.nodes.source'); sources.discover()",
                "transforms = EntryPointRegistry('rfgen.nodes.transform'); transforms.discover()",
                "assert sources.load_class('fixture_tone').__name__ == 'FixtureSource'",
                "assert transforms.load_class('fixture_channel').__name__ == 'FixtureTransform'",
                "assert 'fixture' in storage_names()",
                "storage = get_storage('fixture')",
                "shard = storage.write_shard([SceneRecord({})], 'memory://probe', shard_index=0, first_ordinal=0, scene_ids=['probe'])",
                "published = storage.publish_shards([shard], 'memory://probe', dataset_id='probe', snapshot_id='s0')",
                "assert len(published) == len(storage.open('memory://probe')) == 1",
                "print(json.dumps({'extensions': 'installed', 'storage': 'lifecycle'}))",
            )
        ),
        cwd=tmp_path,
    )
    assert json.loads(result.stdout) == {"extensions": "installed", "storage": "lifecycle"}
    assert wheel.is_file()

    initialized = tmp_path / "fixture-config"
    installed_wheel.run(
        str(installed_wheel.rfgen), "init", "chirp-radar", str(initialized), cwd=tmp_path
    )
    fixture_output = tmp_path / "fixture.records"
    generated = installed_wheel.run(
        str(installed_wheel.rfgen),
        "generate",
        "--config-dir",
        str(initialized),
        "--output",
        str(fixture_output),
        "--num-samples",
        "1",
        "--shard-size",
        "1",
        "storage.format=fixture",
        cwd=tmp_path,
    )
    assert json.loads(generated.stdout.splitlines()[-1])["status"] == "published"
    second_output = tmp_path / "fixture-second.records"
    installed_wheel.run(
        str(installed_wheel.rfgen),
        "generate",
        "--config-dir",
        str(initialized),
        "--output",
        str(second_output),
        "--num-samples",
        "1",
        "--shard-size",
        "1",
        "storage.format=fixture",
        cwd=tmp_path,
    )
    inspected = installed_wheel.run(
        str(installed_wheel.rfgen),
        "inspect",
        str(fixture_output),
        "--storage-format",
        "fixture",
        "--compare-to",
        str(second_output),
        cwd=tmp_path,
    )
    payload = json.loads(inspected.stdout)
    assert payload["comparison_equal"] is True
    assert payload["report"]["record_count"] == 1


@pytest.mark.e2e
def test_invalid_external_selector_fails_at_public_registry_boundary(
    installed_wheel: InstalledWheel, tmp_path: Path
) -> None:
    _build_and_install_fixture(installed_wheel, tmp_path)
    result = installed_wheel.run(
        str(installed_wheel.python),
        "-c",
        "from rfgen.plugins import EntryPointRegistry; registry = EntryPointRegistry('rfgen.nodes.source'); registry.discover(); registry.load_class('missing_fixture')",
        cwd=tmp_path,
        check=False,
    )
    assert result.returncode != 0
    assert "missing_fixture" in result.stderr
    assert "PluginNotFoundError" in result.stderr
