"""Smoke tests for source-distribution packaging."""

from __future__ import annotations

import json
import os
import shutil
import subprocess
import sys
import tarfile
from pathlib import Path


def test_sdist_includes_agent_assets(tmp_path: Path) -> None:
    repo_root = Path(__file__).resolve().parents[1]
    uv = shutil.which("uv")
    if uv is None:
        raise AssertionError(
            "uv executable is required to build the source distribution smoke test"
        )

    subprocess.run(
        [uv, "build", "--sdist", "--out-dir", str(tmp_path)],
        check=True,
        cwd=repo_root,
        capture_output=True,
        text=True,
    )

    artifacts = sorted(tmp_path.glob("*.tar.gz"))
    assert artifacts, "uv build --sdist did not produce a source distribution"

    with tarfile.open(artifacts[0], "r:gz") as archive:
        members = {member.name for member in archive.getmembers()}

    expected_suffixes = {
        "AGENTS.md",
        "CAPABILITIES.md",
        "agent-snippets/downstream-AGENTS.md",
        "examples/playwright_programmatic_capture.py",
        "examples/playwright_motion_snapshot.py",
        "examples/cli_jsonl_batch_capture.py",
        "examples/custom_viewport_and_html_snapshot.py",
        "examples/selenium_programmatic_capture.py",
        "examples/playwright_scrolling_depth_capture.py",
        "examples/service_batch_capture.py",
        "examples/storage_summary_integration.py",
        "skills/infra-screenshot-local-cli/SKILL.md",
        "skills/infra-screenshot-local-cli/agents/openai.yaml",
        "skills/infra-screenshot-playwright-capture/SKILL.md",
        "skills/infra-screenshot-playwright-capture/agents/openai.yaml",
        "skills/infra-screenshot-selenium-capture/SKILL.md",
        "skills/infra-screenshot-selenium-capture/agents/openai.yaml",
        "skills/infra-screenshot-service-storage/SKILL.md",
        "skills/infra-screenshot-service-storage/agents/openai.yaml",
    }

    for suffix in expected_suffixes:
        assert any(
            member.endswith(suffix) for member in members
        ), f"Missing {suffix} from source distribution"


def test_wheel_exposes_library_first_public_api(tmp_path: Path) -> None:
    repo_root = Path(__file__).resolve().parents[1]
    uv = shutil.which("uv")
    if uv is None:
        raise AssertionError("uv executable is required to build the wheel smoke test")

    subprocess.run(
        [uv, "build", "--wheel", "--out-dir", str(tmp_path)],
        check=True,
        cwd=repo_root,
        capture_output=True,
        text=True,
    )

    artifacts = sorted(tmp_path.glob("*.whl"))
    assert artifacts, "uv build --wheel did not produce a wheel"

    env = dict(os.environ)
    env["PYTHONPATH"] = str(artifacts[0])
    script = """
import importlib.util
import json

import screenshot
import screenshot.backends
import screenshot.capabilities

print(json.dumps({
    "module_file": screenshot.__file__,
    "has_backends": hasattr(screenshot, "backends"),
    "has_capabilities": hasattr(screenshot, "capabilities"),
    "has_motion_request": hasattr(screenshot, "MotionSnapshotRequest"),
    "has_artifact_request": hasattr(screenshot, "ScreenshotArtifactsRequest"),
    "has_removed_job_spec": hasattr(screenshot, "ScreenshotJobSpec"),
    "has_removed_metadata": hasattr(screenshot, "ScreenshotMetadata"),
    "has_removed_resource_result": hasattr(screenshot, "ScreenshotResourceResult"),
    "backend_factory": hasattr(screenshot.backends, "build_local_screenshot_service"),
    "has_internal_spec": importlib.util.find_spec("screenshot._internal") is not None,
    "has_cli_config_spec": importlib.util.find_spec("screenshot.cli_config") is not None,
}))
""".strip()
    proc = subprocess.run(
        [
            sys.executable,
            "-c",
            script,
        ],
        check=True,
        cwd=tmp_path,
        env=env,
        capture_output=True,
        text=True,
    )

    payload = json.loads(proc.stdout)
    assert ".whl" in payload["module_file"]
    assert payload["has_backends"] is True
    assert payload["has_capabilities"] is True
    assert payload["has_motion_request"] is True
    assert payload["has_artifact_request"] is True
    assert payload["backend_factory"] is True
    assert payload["has_removed_job_spec"] is False
    assert payload["has_removed_metadata"] is False
    assert payload["has_removed_resource_result"] is False
    assert payload["has_internal_spec"] is False
    assert payload["has_cli_config_spec"] is False
