from __future__ import annotations

import importlib.util
import sys
from pathlib import Path
from types import ModuleType
from typing import Any, cast

import pytest

from screenshot import ScreenshotCaptureResult
from screenshot._shared.errors import make_error


def _load_module(name: str, path: Path) -> ModuleType:
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise AssertionError(f"Unable to load module from {path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


@pytest.mark.asyncio
async def test_perf_script_run_once_uses_outcome_status_not_removed_property(
    tmp_path: Path,
) -> None:
    module = _load_module(
        "perf_screenshot_script",
        Path(__file__).resolve().parents[1] / "scripts" / "perf_screenshot.py",
    )
    module_any = cast(Any, module)

    async def fake_capture(*_args: object, **_kwargs: object) -> ScreenshotCaptureResult:
        return ScreenshotCaptureResult(
            requested=1,
            captured=1,
            failed=1,
            metadata_path=None,
            entries=[
                {
                    "attempts": 2,
                    "scroll_height": 2048,
                    "error": "timed out after capture",
                    "timings": {"navigate_ms": 12.5},
                }
            ],
            errors=[make_error("timeout", "timed out after capture")],
            job_id="demo",
        )

    module_any.capture_screenshots_async = fake_capture
    scenario = module_any.Scenario(
        name="demo",
        path="/",
        capture_overrides={"scroll": False, "full_page": False},
    )

    record = await module_any._run_once(
        base_url="http://example.test",
        scenario=scenario,
        artifacts_dir=tmp_path,
    )

    assert record["status"] == "partial"
    assert record["attempts"] == 2
    assert record["scroll_height"] == 2048
    assert record["timings"] == {"navigate_ms": 12.5}
