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

The recipe IS a content server (nginx serving /usr/share/nginx/html). Its characteristic behavior is
**serve persisted content**, not "returns 200". So write a uniquely-marked file into the served
volume and fetch it back over HTTPS — proves the app serves what's in the volume, not a hardcoded
default page.

Runs in the custom tier against the shared post-install deployment (live_app). No deploy/teardown.
"""

from __future__ import annotations

import os
import sys
import uuid

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


def test_content_roundtrip(live_app):
    """Write a uniquely-marked .txt file into nginx's served volume, fetch it over HTTPS, assert the
    exact bytes round-trip. Non-vacuous: a stale page or misrouted backend would not return our
    randomly-generated content."""
    marker = f"ccci-roundtrip-{uuid.uuid4().hex}"
    # written into the served volume; nginx routes /<filename> to /usr/share/nginx/html/<filename>
    filename = f"ccci-roundtrip-{uuid.uuid4().hex[:12]}.txt"
    lifecycle.exec_in_app(
        live_app,
        ["sh", "-c", f"printf %s {marker} > /usr/share/nginx/html/{filename}"],
    )

    url = f"https://{live_app}/{filename}"
    # short retry: nginx serves the file off the live volume as soon as it lands; the retry is
    # belt-and-suspenders against any FS-cache latency.
    deadline_wait = 15
    last_status, last_body = 0, ""
    for _ in range(deadline_wait):
        last_status, last_body = lifecycle.http_fetch(live_app, f"/{filename}", timeout=10)
        if last_status == 200 and last_body == marker:
            break
        import time

        time.sleep(1)
    assert last_status == 200, f"GET {url} -> HTTP {last_status} (expected 200)"
    assert last_body == marker, (
        f"GET {url} returned {last_body!r}, expected {marker!r} — "
        "the served volume did not round-trip"
    )
    # Also prove it via the harness_http helper (consistent with Phase-2 canonical API)
    status, parsed = harness_http.http_get(url)
    assert status == 200
    # plain text, not JSON — parsed should be None (http_get only returns json_or_None)
    assert parsed is None or parsed == marker
