"""discourse — Q4.6 recipe-specific functional test (plan §4.3: "create the app's primary object — a
topic — and read it back").

Exercises Discourse's core forum function end-to-end against the live per-run deploy, via the real
Admin API:
  1. Wait for the Admin API to answer (/site.json 200 once Rails is serving).
  2. Bootstrap an admin + mint an API key (_discourse.mint_admin — the recipe seeds no admin).
  3. POST /posts.json to create a new topic (title + body carrying a unique marker).
  4. GET /t/<topic_id>.json to read it back and assert the title round-tripped; GET the post's raw
     and assert the unique body marker survived.

NOT health-only: a Discourse whose DB/Rails/posting path is broken fails here even though /srv/status
returns 200. The marker is unique per run, so a stale/echoed response cannot pass.
"""

from __future__ import annotations

import os
import sys
import uuid

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


def test_create_topic_roundtrip(live_app):
    base = f"https://{live_app}"

    # 1) Admin API ready (Rails serving JSON, not just /srv/status).
    harness_http.retry_http_get(f"{base}/site.json", expect_status=200, max_wait=120, interval=5)

    # 2) Bootstrap admin + API key (recipe seeds no admin; mint via Rails in the app container).
    api_key, api_user = _discourse.mint_admin(live_app)
    hdrs = _discourse.admin_headers(api_key, api_user)

    # 3) Create a topic with a unique marker in title + body (raw must be >= ~20 chars).
    # Discourse's `title_prettify` (on by default) capitalises the title's first letter, so we send a
    # title that already starts capitalised — that normalisation is then a no-op and the exact-equality
    # round-trip below stays faithful (the unique hex token is mid-string, untouched either way).
    uniq = uuid.uuid4().hex[:10]
    title = f"CCCI topic {uniq}"
    marker = f"ccci-body-marker-{uniq}-roundtrip-padding-text"
    status, body = harness_http.http_post(
        f"{base}/posts.json",
        data={"title": title, "raw": marker},
        headers=hdrs,
        timeout=60,
    )
    assert status in (200, 201) and isinstance(body, dict), (
        f"create topic failed: HTTP {status}, body={body!r}"
    )
    topic_id = body.get("topic_id")
    assert topic_id, f"create topic returned no topic_id: {body!r}"

    # 4) Read the topic back and assert title + first-post body round-trip.
    status, got = harness_http.http_get(f"{base}/t/{topic_id}.json", headers=hdrs, timeout=30)
    assert status == 200 and isinstance(got, dict), (
        f"read topic failed: HTTP {status}, body={got!r}"
    )
    assert got.get("title") == title, (
        f"topic title did not round-trip: sent {title!r}, got {got.get('title')!r}"
    )
    posts = (got.get("post_stream") or {}).get("posts") or []
    assert posts, f"topic has no posts on read-back: {got!r}"
    first_cooked = posts[0].get("cooked", "")
    assert marker in first_cooked, (
        f"topic body did not round-trip: marker {marker!r} not in first post {first_cooked!r}"
    )
