import sys

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


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

view = QWebEngineView()
view.setObjectName("armorEmbeddedAgentWorkspaceTest")

html = """
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ARMOR Embedded Agent Test</title>
</head>
<body>
<h1>ARMOR EMBEDDED AGENT WORKSPACE</h1>
<p>Qt WebEngine rendering test.</p>
</body>
</html>
"""

state = {
    "loaded": False,
    "success": False,
}


def loaded(success):
    state["loaded"] = True
    state["success"] = bool(success)

    print("loadFinished:", bool(success))
    print("title:", view.title())
    print("objectName:", view.objectName())

    QTimer.singleShot(100, app.quit)


view.loadFinished.connect(loaded)
view.setHtml(html)

QTimer.singleShot(8000, app.quit)

exit_code = app.exec_()

if not state["loaded"]:
    raise SystemExit(
        "FAIL: QWebEngineView did not complete its load event."
    )

if not state["success"]:
    raise SystemExit(
        "FAIL: QWebEngineView reported an unsuccessful page load."
    )

if view.title() != "ARMOR Embedded Agent Test":
    raise SystemExit(
        f"FAIL: Unexpected rendered title: {view.title()!r}"
    )

print("QWEBENGINE VIEW CONSTRUCTION: PASS")
print("QWEBENGINE HTML RENDERING: PASS")
print("QWEBENGINE EVENT LOOP: PASS")

view.deleteLater()
raise SystemExit(exit_code)
