"""ghost — recipe-specific functional test (Phase 2 P3).

Ghost's admin UI lives at `/ghost/`. On a fresh deploy with no owner yet, /ghost/ redirects
(302) to the setup wizard at `/ghost/#/setup`. On a deployment with an owner already set up,
/ghost/ shows the login form (200 with a login HTML). Either way, GET /ghost/ should NOT
return 404 — that would indicate the admin route is not wired.

This test asserts /ghost/ returns 200 or 302 (admin route exists), and the response is HTML
that references Ghost's admin client (the /ghost-assets/ path or 'ghost' in the response body).

Non-vacuous: a misrouted nginx returns 404; a wedged ghost-server returns 502/504; only a
correctly-wired Ghost serves the admin SPA shell or its setup redirect.
"""

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_html(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")
    try:
        with urllib.request.urlopen(req, timeout=15, context=ctx) as r:
            return r.status, r.read().decode(errors="replace")
    except urllib.error.HTTPError as e:
        # urllib doesn't auto-follow 302 by default but might raise — handle anyway
        try:
            body = e.read().decode(errors="replace")
        except Exception:  # noqa: BLE001
            body = ""
        return e.code, body
    except Exception:  # noqa: BLE001
        return 0, ""


def test_ghost_admin_route_is_wired(live_app):
    """GET /ghost/ → 200 or 302; body references Ghost admin (or redirects to /ghost/#/setup)."""
    url = f"https://{live_app}/ghost/"

    def _ready():
        s, body = _get_html(url)
        if s in (200, 302) and ("ghost" in body.lower() or s == 302):
            return (s, body)
        return None

    status_body = harness_http.assert_converges(
        _ready,
        f"GET {url} returns Ghost admin (200) or setup redirect (302)",
        max_wait=60,
        interval=3,
    )
    status, body = status_body
    assert status in (200, 302), f"unexpected status: {status}"
    if status == 200:
        # The admin SPA references /ghost-assets/ or contains "ghost" in title/body
        assert "ghost" in body.lower(), (
            f"GET {url} 200 but body has no Ghost markers: {body[:200]!r}"
        )
