"""cryptpad — recipe-specific functional test (Phase 2 P3, ≥2 beyond parity).

CryptPad's served SPA at `/` carries distinctive markers — a CryptPad-branded HTML page that
loads specific known asset paths (`/customize/main.js` is the canonical entry point on every
CryptPad version) and references CryptPad-specific strings (e.g. "CryptPad" in the page title,
`/components/` for the SPA's bundled JS deps). A working cryptpad-server emits this; a broken one
(SPA build missing, nginx misrouted) emits something else even when /healthz / `/` are 200.

This test fetches `/` and asserts:
1. The HTML contains the string "CryptPad" (case-insensitive) somewhere — page title, branding,
   or asset references.
2. The HTML references at least one of the canonical CryptPad-bundled asset paths
   (`/customize/`, `/components/`, or `/api/broadcast`) — proves the SPA bundle is bound, not
   just some empty default page.

Non-vacuous: an nginx serving an empty default page (or a misconfigured cryptpad-server replaced
by a fallback) would 200 the parity test but fail BOTH markers here.

Runs in the custom tier against the shared post-install deployment.
"""

from __future__ import annotations

import os
import ssl
import sys
import urllib.request

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
from harness import http as harness_http  # noqa: E402


def _get_body(url: str) -> tuple[int, str]:
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    req = urllib.request.Request(url, method="GET")
    with urllib.request.urlopen(req, timeout=15, context=ctx) as r:
        return r.status, r.read().decode(errors="replace")


def test_cryptpad_spa_has_recipe_specific_markers(live_app):
    """GET /; assert CryptPad-specific HTML markers (branding + canonical asset paths)."""
    url = f"https://{live_app}/"

    # Poll for the body in case the SPA's first response is slow to assemble
    def _ready():
        try:
            status, body = _get_body(url)
        except Exception:  # noqa: BLE001
            return None
        if status != 200:
            return None
        return body

    body = harness_http.assert_converges(
        _ready, f"GET {url} returns 200 with body", max_wait=60, interval=3
    )

    lower = body.lower()
    # Marker 1: the "CryptPad" branding string must be present somewhere
    assert "cryptpad" in lower, (
        f"GET {url} HTML does not contain 'CryptPad' branding — the SPA may be misrouted "
        f"or a placeholder is being served. Body excerpt: {body[:200]!r}"
    )
    # Marker 2: at least one of CryptPad's canonical asset path references must appear
    canonical_paths = ("/customize/", "/components/", "/api/broadcast", "main.js")
    present = [p for p in canonical_paths if p in body]
    assert present, (
        f"GET {url} HTML references NONE of {canonical_paths} — the CryptPad SPA bundle is "
        f"not bound. Body excerpt: {body[:300]!r}"
    )
