import json
import sys

from PyQt5.QtCore import QTimer, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView


URL = "http://127.0.0.1:8785/agents/scanforge/"

app = QApplication.instance() or QApplication(sys.argv)

view = QWebEngineView()
view.resize(1600, 880)

result = {
    "loaded": False,
    "layout": None,
}


def finish_with_error(message):
    print(message)
    app.exit(1)


def inspect_layout(successful):
    if not successful:
        finish_with_error(
            "FAIL: ScanForge page did not load."
        )
        return

    script = """
    (() => {
      const root = document.getElementById('root');
      const bodyStyle = getComputedStyle(document.body);
      const htmlStyle = getComputedStyle(document.documentElement);
      const rootStyle = root ? getComputedStyle(root) : null;

      return {
        innerWidth: window.innerWidth,
        innerHeight: window.innerHeight,
        htmlHeight: document.documentElement.getBoundingClientRect().height,
        bodyHeight: document.body.getBoundingClientRect().height,
        rootHeight: root ? root.getBoundingClientRect().height : 0,
        bodyBackground: bodyStyle.backgroundColor,
        htmlBackground: htmlStyle.backgroundColor,
        rootBackground: rootStyle ? rootStyle.backgroundColor : null,
        bodyOverflow: bodyStyle.overflow,
        rootOverflow: rootStyle ? rootStyle.overflow : null
      };
    })();
    """

    def inspected(value):
        result["loaded"] = True
        result["layout"] = value
        print(json.dumps(value, indent=2))
        QTimer.singleShot(100, app.quit)

    view.page().runJavaScript(
        script,
        inspected,
    )


view.loadFinished.connect(inspect_layout)
view.load(QUrl(URL))

QTimer.singleShot(
    15000,
    lambda: finish_with_error(
        "FAIL: ScanForge viewport test timed out."
    ),
)

app.exec_()

if not result["loaded"]:
    raise SystemExit(1)

layout = result["layout"]
viewport = float(layout["innerHeight"])

for key in (
    "htmlHeight",
    "bodyHeight",
    "rootHeight",
):
    actual = float(layout[key])

    if actual < viewport - 3:
        raise SystemExit(
            f"FAIL: {key} is only {actual}px "
            f"for a {viewport}px viewport."
        )

white_values = {
    "rgb(255, 255, 255)",
    "rgba(255, 255, 255, 1)",
}

if layout["bodyBackground"] in white_values:
    raise SystemExit(
        "FAIL: Body background is still white."
    )

if layout["htmlBackground"] in white_values:
    raise SystemExit(
        "FAIL: HTML background is still white."
    )

print("Full-height HTML viewport: PASS")
print("Full-height body viewport: PASS")
print("Full-height React root: PASS")
print("Dark embedded background: PASS")
print("White lower panel: ELIMINATED")
