from __future__ import annotations

import os
from pathlib import Path

import pytest

from nomo_e2e.controller import WebViewController
from nomo_e2e.discovery import WebViewDiscovery


@pytest.mark.skipif(
    os.getenv("WEBDRIVER_SMOKE") != "1",
    reason="Set WEBDRIVER_SMOKE=1 to run real WebDriver smoke test",
)
def test_webdriver_smoke(tmp_path: Path) -> None:
    endpoint = os.getenv("WEBDRIVER_ENDPOINT", "http://127.0.0.1:4445")
    selector = os.getenv("WEBDRIVER_SMOKE_SELECTOR", "body")
    app_keyword = os.getenv("WEBDRIVER_APP_KEYWORD", "GoldenIdea")
    title_keyword = os.getenv("WEBDRIVER_TITLE_KEYWORD", "GoldenIdea")
    url_keyword = os.getenv("WEBDRIVER_URL_KEYWORD", "/idea")
    screenshot_path = tmp_path / "webdriver-smoke.png"
    discovery = WebViewDiscovery()
    matched_webviews = discovery.find_by_name(app_keyword)
    assert matched_webviews, f"No running app matched keyword: {app_keyword}"
    controller = WebViewController.connect(endpoint, driver="webdriver")
    try:
        controller.wait_for_load_state("interactive", timeout_ms=15000)
        assert controller.wait_for_selector(selector, timeout_ms=10000)
        ready_state = controller.execute_script("return document.readyState")
        page_title = controller.title
        current_url = controller.url
        tauri_ready = controller.execute_script(
            """
            const api = globalThis.__TAURI__;
            const internals = globalThis.__TAURI_INTERNALS__;
            if (api && typeof api.invoke === 'function') return 'root';
            if (api && api.core && typeof api.core.invoke === 'function') return 'core';
            if (internals && typeof internals.invoke === 'function') return 'internals';
            return 'missing';
            """
        )
        assert ready_state in {"interactive", "complete"}
        assert (
            title_keyword.lower() in page_title.lower()
            or url_keyword.lower() in current_url.lower()
            or "tauri://" in current_url.lower()
        )
        assert tauri_ready in {"root", "core", "internals"}
        image = controller.screenshot(str(screenshot_path))
        assert image
        assert screenshot_path.exists()
    except Exception as exc:
        diagnostics: dict[str, object]
        try:
            diagnostics = controller.diagnostics_snapshot()
            diagnostics["matched_webviews"] = [wv.name for wv in matched_webviews]
        except Exception as diagnostics_exc:
            diagnostics = {"diagnostics_error": str(diagnostics_exc)}
        pytest.fail(f"WebDriver smoke failed: error={exc}, diagnostics={diagnostics}")
    finally:
        controller.disconnect()
