"""hedgedoc — branding probe: served HTML carries hedgedoc/codimd markers.

Distinguishes "the HedgeDoc app is bound and serving its own content" from "a generic 200
from a fallback page." A wedged backend or misconfigured proxy would lack these markers.
"""

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

_CTX = ssl.create_default_context()
_CTX.check_hostname = False
_CTX.verify_mode = ssl.CERT_NONE


def _get_body(url: str) -> tuple[int, str]:
    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_hedgedoc_has_branding(live_app):
    """GET /; assert HedgeDoc-specific brand/asset markers in served HTML."""
    url = f"https://{live_app}/"

    def _ready():
        try:
            status, body = _get_body(url)
        except Exception:  # noqa: BLE001
            return None
        # 200 = full page; 302 = redirect (follow manually not needed — just the HTML response)
        return body if status in (200, 302) else None

    body = harness_http.assert_converges(_ready, f"GET {url}", max_wait=90, interval=5)
    lower = body.lower()
    # HedgeDoc brand markers: any of "hedgedoc", "codimd" (the older brand), or the app meta tag
    brand_markers = ("hedgedoc", "codimd", "hackmd")
    present_brand = [m for m in brand_markers if m in lower]

    # SPA asset markers: CSS/JS bundles or the favicon that HedgeDoc serves
    asset_markers = ("/assets/", "/vendor.", "favicon", "bundle.", ".js")
    present_assets = [m for m in asset_markers if m in body]

    assert present_brand or present_assets, (
        f"GET {url} HTML contains none of {brand_markers} or {asset_markers}. "
        f"Excerpt: {body[:300]!r}"
    )
