"""wordpress — complete the install wizard, then read the site back via the REST API.

Non-vacuous: the install POST writes the site options + admin user to mariadb through the
app's DB wiring; `/wp-json/` only returns the site name after WP can read those options back
from the DB, and the pretty-permalink REST route additionally proves the recipe's .htaccess
rewrites are live. A wedged DB fails the install; a missing htaccess breaks /wp-json/ (the
`?rest_route=` fallback is asserted separately so the failure names the broken layer).
"""

from __future__ import annotations

import os
import sys

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


def test_install_and_rest_api_roundtrip(live_app):
    ensure_installed(live_app)

    # ?rest_route= works regardless of rewrites — isolates "REST API up + DB readable"
    status, body = harness_http.http_get(f"https://{live_app}/?rest_route=/", timeout=60)
    assert status == 200, f"GET /?rest_route=/ HTTP {status}"
    assert isinstance(body, dict), f"REST index is not JSON: {body!r}"
    assert body.get("name") == BLOG_TITLE, (
        f"site name mismatch: got {body.get('name')!r}, expected {BLOG_TITLE!r} — "
        "install options did not round-trip through the DB"
    )

    # /wp-json/ additionally requires the recipe's .htaccess rewrite rules
    status, body = harness_http.http_get(f"https://{live_app}/wp-json/", timeout=60)
    assert status == 200, (
        f"GET /wp-json/ HTTP {status} — REST works via ?rest_route= but the pretty route "
        "fails: the recipe's .htaccess rewrites are not active"
    )
    assert isinstance(body, dict) and body.get("name") == BLOG_TITLE, (
        f"unexpected /wp-json/ payload: {body!r}"
    )
