"""cryptpad — §4.3 create-an-object + read-it-back (Phase 2 P3 + P6); resolves F2-9.

CryptPad is end-to-end client-side encrypted: the server only ever stores ciphertext, and the
decryption key lives in the URL fragment (`#/2/pad/edit/<key>/`). So "create a pad, confirm it
persists" cannot be done with bare curl (plan §4.3 note) — it must be a real browser flow. This test
proves genuine persistence of decrypted content across a FRESH browser session:

1. Open `/pad/` in a browser; CryptPad auto-creates a new anonymous pad and writes the edit URL
   (fragment-keyed) into the address bar. Capture that full URL.
2. Type a unique marker into the CKEditor rich-text body (nested sandbox iframe).
3. Wait for CryptPad to sync the encrypted update to the server ("Saved").
4. Open a **brand-new browser context** (no shared localStorage/cookies — a different "session")
   and navigate to the captured pad URL.
5. Assert the unique marker is present in the re-decrypted pad body.

Step 4's fresh context is the real proof: the only thing carried over is the URL (incl. its
fragment key), so a successful read-back means the content was persisted server-side (encrypted) and
correctly decrypted by a new client — not merely cached locally. This is the §4.3 create-and-read-back
floor for CryptPad, not a health/SPA-render stand-in.

Empirically mapped against the recipe under test (CryptPad 2026.2.0): the editor lives in a deeply
nested frame `…/pad/ckeditor-inner.html` (top page → `#sbox-iframe` on the sandbox domain → CKEditor
frame); first init compiles LESS (~15s on a cold cache), so the frame hunt and hash wait are patient.
Transient `net::ERR_NETWORK_CHANGED` is handled by the shared `goto_with_retry` (F2-3).
"""

from __future__ import annotations

import contextlib
import os
import sys
import uuid

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


def _open_pad(ctx, url):
    """Open `url`, wait for full init, and return (page, pad_edit_url). The pad URL is the address
    bar once CryptPad has created/loaded the fragment-keyed pad (`#/2/pad/edit/<key>/`)."""
    page = ctx.new_page()
    harness_browser.goto_with_retry(
        page,
        url,
        accept_statuses=(200,),
        goto_timeout_ms=60_000,
        wait_until="load",
        deadline_seconds=150,
    )
    pad_url = url
    # Up to ~240s for CryptPad to create/load the fragment-keyed pad. A FRESH per-run deploy is
    # cold (server datastore + LESS compile + first-ever websocket), and `/` → 200 (the recipe
    # health gate) can be reached before CryptPad's API is ready to mint a pad — so be patient and,
    # if no pad after ~80s, reload once to unstick a load that stalled before pad creation.
    for i in range(120):
        page.wait_for_timeout(2000)
        if "#/2/pad/edit/" in page.url:
            pad_url = page.url
            break
        if i == 40:
            with contextlib.suppress(Exception):  # best-effort unstick
                harness_browser.goto_with_retry(
                    page,
                    url,
                    accept_statuses=(200,),
                    goto_timeout_ms=60_000,
                    wait_until="load",
                    deadline_seconds=120,
                )
    return page, pad_url


def _ckeditor_frame(page, deadline_polls=90, reload_at=22, reload_url=None):
    """Return CryptPad's CKEditor content frame (`…/pad/ckeditor-inner.html`), polling for it to
    attach. It loads after the sandbox iframe + a cold-cache LESS compilation (~15s+), and a FRESH
    browser context re-downloads/recompiles everything, which under this env's hairpin network can be
    slow/flaky — so be patient (up to ~deadline_polls*2s) and, halfway, do ONE reload to unstick a
    load that stalled on a transient net error."""
    for i in range(deadline_polls):
        for f in page.frames:
            if "ckeditor-inner" in f.url:
                return f
        if i == reload_at and reload_url is not None:
            with contextlib.suppress(Exception):  # reload is a best-effort unstick
                harness_browser.goto_with_retry(
                    page,
                    reload_url,
                    accept_statuses=(200,),
                    goto_timeout_ms=60_000,
                    wait_until="load",
                    deadline_seconds=120,
                )
        page.wait_for_timeout(2000)
    return None


def _poll_any_frame_for_text(
    page, needle, deadline_polls=120, reload_at=(20, 45, 75, 100), reload_url=None
):
    """Robust read-back (F2-13): poll EVERY frame's body text for `needle`, returning True as soon as
    it appears. The fresh cold-cache read-back context's deeply-nested CKEditor frame is slow/flaky to
    *attach* by URL (the prior `_ckeditor_frame` wait timed out on the Adversary's cold run), but the
    decrypted pad content lands in whichever frame renders it — so we don't require a specific frame,
    we just watch all of them for the marker. Reload periodically to unstick a stalled cold load.
    Generous deadline (~deadline_polls*2s) since the fresh context recompiles LESS + re-fetches +
    decrypts. Returns False if the marker never appears (genuine non-persistence)."""
    for i in range(deadline_polls):
        for f in page.frames:
            try:
                if needle in (f.locator("body").inner_text(timeout=2000) or ""):
                    return True
            except Exception:  # noqa: BLE001 — frame not ready / detached; keep polling
                pass
        if reload_url and i in reload_at:
            with contextlib.suppress(Exception):  # best-effort unstick
                harness_browser.goto_with_retry(
                    page,
                    reload_url,
                    accept_statuses=(200,),
                    goto_timeout_ms=60_000,
                    wait_until="load",
                    deadline_seconds=120,
                )
        page.wait_for_timeout(2000)
    return False


def _dismiss_store_modal(page):
    """Anonymous pads prompt 'store in CryptDrive?'. Dismiss it (DON'T STORE) so it can't intercept
    editor clicks. Non-fatal if absent."""
    for f in page.frames:
        try:
            btn = f.get_by_text("DON'T STORE", exact=False)
            if btn.count():
                btn.first.click(timeout=3000)
                return
        except Exception:  # noqa: BLE001 — best-effort modal dismissal
            pass


def test_cryptpad_pad_content_survives_fresh_session(live_app):
    """Create a pad, type a unique marker, then read it back from a FRESH browser context via the
    fragment-keyed URL — proving end-to-end-encrypted content persisted server-side (§4.3)."""
    from playwright.sync_api import sync_playwright

    marker = f"CCCI-PAD-{uuid.uuid4().hex[:12].upper()}"
    with sync_playwright() as p:
        browser = p.chromium.launch(args=["--no-sandbox"])
        try:
            # --- session 1: create the pad + write the marker ---
            ctx1 = browser.new_context(ignore_https_errors=True)
            page, pad_url = _open_pad(ctx1, f"https://{live_app}/pad/")
            assert "#/2/pad/edit/" in pad_url, (
                f"CryptPad did not create a fragment-keyed pad URL; got {pad_url!r}"
            )
            ck = _ckeditor_frame(page, reload_url=pad_url)
            assert ck is not None, "CKEditor content frame never attached (pad editor not ready)"
            _dismiss_store_modal(page)
            body = ck.locator("body")
            body.click()
            page.wait_for_timeout(1000)
            body.type(marker, delay=40)
            page.wait_for_timeout(12000)  # let CryptPad encrypt + sync the update to the server
            assert marker in ck.locator("body").inner_text(), (
                "marker not present in the editor after typing — type did not land"
            )
            ctx1.close()

            # --- session 2: FRESH context (no shared storage/localStorage) reads the pad back by URL.
            # Robust read-back (F2-13): poll ALL frames for the marker (don't require the CKEditor
            # frame to attach — that's the flaky part on a cold fresh context). The marker appearing
            # in a brand-new session proves the content was persisted server-side (encrypted) and
            # decrypted from only the URL+fragment key.
            ctx2 = browser.new_context(ignore_https_errors=True)
            page2, _ = _open_pad(ctx2, pad_url)
            found = _poll_any_frame_for_text(page2, marker, reload_url=pad_url)
            assert found, (
                f"marker {marker!r} did NOT survive into a fresh session — content not persisted/"
                "decrypted (polled all frames + reloads to a generous deadline)"
            )
        finally:
            browser.close()
