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")

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


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

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

    QTimer.singleShot(150, app.quit)


view.loadFinished.connect(finish)

view.setHtml(
    """
    <!doctype html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>ARMOR Embedded Agent Test</title>
      </head>
      <body>
        <h1>ARMOR EMBEDDED AGENT WORKSPACE</h1>
        <nav>
          <button>HOME</button>
          <button>BACK TO AGENTS</button>
          <button>RELOAD</button>
        </nav>
      </body>
    </html>
    """
)

QTimer.singleShot(8000, app.quit)
app.exec_()

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

if not state["success"]:
    raise SystemExit(
        "FAIL: QWebEngineView reported an unsuccessful 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.setPage(None)
view.deleteLater()
app.processEvents()
