#!/usr/bin/env python3
"""Quick smoke test: verify Playwright can reach the Central UI through Traefik."""

import sys
from playwright.sync_api import sync_playwright

# The browser runs inside Docker, so use the Docker network hostname for Traefik.
# The Playwright server WebSocket is exposed to the host on port 3000.
TRAEFIK_URL = "http://scadabridge-traefik"
PLAYWRIGHT_WS = "ws://localhost:3000"


def main():
    with sync_playwright() as p:
        print(f"Connecting to Playwright server at {PLAYWRIGHT_WS} ...")
        browser = p.chromium.connect(PLAYWRIGHT_WS)

        page = browser.new_page()
        print(f"Navigating to {TRAEFIK_URL} ...")
        response = page.goto(TRAEFIK_URL, wait_until="networkidle", timeout=15000)

        status = response.status if response else None
        title = page.title()
        url = page.url

        print(f"  Status: {status}")
        print(f"  Title:  {title}")
        print(f"  URL:    {url}")

        # Check for the login page (unauthenticated users get redirected)
        has_login = page.locator("input[type='password'], form[action*='login'], button:has-text('Login'), button:has-text('Sign in')").count() > 0
        if has_login:
            print("  Login form detected: YES")

        browser.close()

        if status and 200 <= status < 400:
            print("\nSMOKE TEST PASSED: Central UI is reachable through Traefik.")
            return 0
        else:
            print(f"\nSMOKE TEST FAILED: unexpected status {status}")
            return 1


if __name__ == "__main__":
    sys.exit(main())
