"""Option D complete (18 Nov 2026): items brought into D from Codex's work and the locked templates.
Synthetic / example data only."""
import copy, json, datetime as dt
from pathlib import Path

import pytest

import generator
import rating

TODAY = dt.date(2026, 11, 18)
HERE = Path(__file__).resolve().parents[1]
PAID = json.loads((HERE / "data/ato/example-flight-academy.json").read_text())
OLD = "2026-01-01"


def render(tmp_path, ato, viewer=None, name="o"):
    d = tmp_path / ("d-" + name)
    d.mkdir(exist_ok=True)
    (d / "a.json").write_text(json.dumps(ato))
    out = tmp_path / name
    generator.build(d, out, "amethyst", TODAY, viewer=viewer)
    return (out / ato["slug"] / "index.html").read_text()


def card(html, rid):
    return html.split(f'data-id="{rid}"', 1)[1].split("</article>", 1)[0]


# ---- 5. Merged-school old reviews (Codex 6f43ca3) ----

def merged_school():
    a = copy.deepcopy(PAID)
    base = a["top_reviews"][0]
    old = {"slug": "old-wings", "name": "Old Wings", "title": "From the old Old Wings page"}
    a["top_reviews"] = [
        dict(copy.deepcopy(base), id="cur1"),
        dict(copy.deepcopy(base), id="old1", old_page=old, duplicate=False, rating_counted=True),
        dict(copy.deepcopy(base), id="old2", old_page=old, duplicate=True, rating_counted=False),
    ]
    a["legacy_slug_targets"] = {"old-wings": {"approval_id": "A1", "anchor": None}}
    return a


def test_old_reviews_group_into_their_own_section_and_cards_are_unchanged(tmp_path):
    html = render(tmp_path, merged_school(), viewer={"kind": "member", "plan": "pro", "name": "someone"})
    assert html.count('class="ob-old-reviews"') == 1
    sec = html.split('class="ob-old-reviews"', 1)[1].split("</section>", 1)[0]
    assert "From the old Old Wings page" in sec and 'data-id="old1"' in sec and 'data-id="old2"' in sec
    assert 'data-id="cur1"' not in sec
    # Same card markup as any other review.
    assert card(html, "old1").split('class="ob-rscore', 1)[0].count("ob-rtop") == card(html, "cur1").split('class="ob-rscore', 1)[0].count("ob-rtop")
    assert "excluded from the school's rating" in card(html, "old2")
    assert "excluded from the school's rating" not in card(html, "old1")


def test_old_address_redirects_to_new_school(tmp_path):
    render(tmp_path, merged_school())
    red = (tmp_path / "o" / "_redirects").read_text()
    assert f"/ato/old-wings /ato/{PAID['slug']} 301" in red
    assert f"/ato/old-wings/ /ato/{PAID['slug']}/ 301" in red


@pytest.mark.parametrize("patch,msg", [
    (lambda r: r.update(old_page={"slug": "Bad Slug", "name": "X", "title": "From the old X page"}), "old page slug"),
    (lambda r: r.update(old_page={"slug": "x", "name": "X", "title": "Wrong"}), "old page title"),
    (lambda r: r.update(old_page={"slug": "x", "name": "X", "title": "From the old X page", "email": "a@b.c"}), "not allowed"),
    (lambda r: r.update(duplicate="yes"), "duplicate must be"),
    (lambda r: r.update(old_page={"slug": "x", "name": "X", "title": "From the old X page"}, duplicate=True, rating_counted=True), "counted"),
    (lambda r: r.update(rating_counted=True), "old-page review only"),
])
def test_old_review_fields_are_checked(patch, msg):
    a = copy.deepcopy(PAID)
    patch(a["top_reviews"][0])
    with pytest.raises(ValueError, match=msg):
        generator.check(a)


def test_bad_legacy_alias_stops_the_build():
    a = copy.deepcopy(PAID)
    a["legacy_slug_targets"] = {"Old Wings": {}}
    with pytest.raises(ValueError, match="legacy alias slug"):
        generator.check(a)


def test_duplicate_review_is_never_counted_twice():
    rows = [{"stars": {"org": n}, "text": "t", "account_created": OLD} for n in (3, 4, 5)]
    base = rating.summarise(rows, TODAY)
    dup = dict(rows[0], stars={"org": 1}, duplicate=True, rating_counted=False, old_page={"slug": "x"})
    with_dup = rating.summarise(rows + [dup], TODAY)
    for k in ("count", "score", "bars", "categories", "shown"):
        assert with_dup[k] == base[k], k


# ---- 6. "Private details removed by moderation" (Codex 34dc14b) ----

def test_privacy_label_under_review_and_official_reply(tmp_path):
    a = copy.deepcopy(PAID)
    rv = next(r for r in a["top_reviews"] if any(p.get("own") for p in r.get("official_replies") or []))
    rv["privacy_redacted"] = True
    next(p for p in rv["official_replies"] if p.get("own"))["privacy_redacted"] = True
    html = render(tmp_path, a)
    c = card(html, rv["id"])
    assert '<p class="ob-edtag">Private details removed by moderation.</p>' in c
    assert "</p><small>Private details removed by moderation.</small>" in c
    other = [r for r in PAID["top_reviews"] if r["id"] != rv["id"] and f'data-id="{r["id"]}"' in html]
    for r in other:
        assert "Private details removed" not in card(html, r["id"])


def test_privacy_label_on_member_reply(tmp_path):
    a = copy.deepcopy(PAID)
    a["top_reviews"][0]["replies"] = [{"id": "m1", "name": "sam", "when": "2026-11-01", "text": "Hi", "privacy_redacted": True}]
    html = render(tmp_path, a, viewer={"kind": "member", "plan": "pro", "name": "zz"})
    rep = html.split('data-id="m1"', 1)[1].split("</div>", 1)[0]
    assert "Private details removed by moderation." in rep


def test_privacy_field_is_allowed_but_other_new_fields_are_not():
    a = copy.deepcopy(PAID)
    a["top_reviews"][0]["privacy_redacted"] = True
    generator.check(copy.deepcopy(a))
    a["top_reviews"][0]["privacy_note"] = "x"
    with pytest.raises(ValueError, match="not allowed"):
        generator.check(a)


# ---- MT 18 Nov 21:49: any signed-in member (Free included) replies anywhere ----

@pytest.mark.parametrize("plan", ["free", "trial", "pro", "founding"])
def test_every_member_plan_can_reply_to_any_review(tmp_path, plan):
    a = copy.deepcopy(PAID)
    html = render(tmp_path, a, viewer={"kind": "member", "plan": plan, "name": "not-an-author"})
    for r in a["top_reviews"]:
        if f'data-id="{r["id"]}"' in html:
            c = card(html, r["id"])
            assert "ob-atg" in c and "ob-rcomp" in c, r["id"]
    assert "Free members can only reply" not in html
    m = generator.page_model(copy.deepcopy(a), TODAY, viewer={"kind": "member", "plan": plan})
    assert m["can"]["reply"] == "anywhere"


def test_free_member_can_reply_to_other_members_replies(tmp_path):
    a = copy.deepcopy(PAID)
    a["top_reviews"][0]["replies"] = [{"id": "m1", "name": "sam", "when": "2026-11-01", "text": "Hi"}]
    html = render(tmp_path, a, viewer={"kind": "member", "plan": "free", "name": "zz"})
    assert 'class="ob-rreply" data-to="m1"' in html


def test_guest_never_gets_reply_controls(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID))
    assert "ob-atg" not in html and "ob-rreply" not in html and "ob-rcomp" not in html


# ---- 1. Up/down votes on replies and replies-to-replies ----

def threaded():
    a = copy.deepcopy(PAID)
    a["top_reviews"][0]["replies"] = [
        {"id": "m1", "name": "sam", "when": "2026-11-01", "text": "Top reply", "up": 4},
        {"id": "m2", "parent_id": "m1", "name": "lee", "when": "2026-11-02", "text": "Reply to reply", "up": 1},
        {"id": "m3", "parent_id": "m2", "name": "kim", "when": "2026-11-03", "text": "Deeper", "mine": True},
    ]
    return a


def reply_html(html, rid):
    return html.split(f'data-id="{rid}"', 1)[1].split('class="ob-reply', 1)[0].split("</article>", 1)[0].split('class="ob-ra"', 1)[0]


def test_members_get_the_review_vote_row_on_every_reply_level(tmp_path):
    html = render(tmp_path, threaded(), viewer={"kind": "member", "plan": "free", "name": "zz"})
    for rid, base in (("m1", 4), ("m2", 1)):
        r = reply_html(html, rid)
        assert f'class="ap-vote ob-vote" data-rid="{rid}" data-base="{base}"' in r
        assert 'class="ap-vb ap-up"' in r and 'class="ap-vb ap-dn"' in r and f'<span class="ap-net" aria-live="polite">{base}</span>' in r


def test_guests_get_no_reply_votes(tmp_path):
    html = render(tmp_path, threaded())
    assert 'data-rid="m1"' not in html and 'data-rid="m2"' not in html


def test_reply_vote_row_uses_the_existing_page_js_handler():
    js = (HERE / "shared/page.js").read_text()
    assert 'e.target.closest(".ob-vote .ap-up, .ob-vote .ap-dn")' in js


# ---- 2. Report button on replies (D's existing report sheet) ----

def test_report_button_on_other_members_replies(tmp_path):
    html = render(tmp_path, threaded(), viewer={"kind": "member", "plan": "free", "name": "zz"})
    for rid in ("m1", "m2"):
        assert '<button type="button" class="ap-vb ap-flag" data-what="reply" aria-label="Report this reply">' in reply_html(html, rid)


def test_report_sheet_reads_data_what_so_it_says_reply():
    js = (HERE / "shared/page.js").read_text()
    assert 'flag.getAttribute("data-what") || "review"' in js and "<h4>Report this ' + what" in js
    assert 'var flag = e.target.closest(".ap-flag");' in js


# ---- 3. No voting on your own review or reply ----

def test_own_reply_votes_disabled_with_your_reply(tmp_path):
    html = render(tmp_path, threaded(), viewer={"kind": "member", "plan": "free", "name": "zz"})
    r = reply_html(html, "m3")
    assert 'class="ap-vote ob-vote is-own" data-rid="m3"' in r
    assert r.count(" disabled>") == 2 and '<span class="ap-own">Your reply</span>' in r and "ap-flag" not in r
    assert " disabled>" not in reply_html(html, "m1")


def test_own_review_votes_disabled_with_your_review(tmp_path):
    a = copy.deepcopy(PAID)
    me = a["top_reviews"][0]
    html = render(tmp_path, a, viewer={"kind": "member", "plan": "pro", "name": "x", "own_id": me["id"]})
    vote = card(html, me["id"]).split('class="ob-ra"', 1)[1]
    assert "ob-vote is-own" in vote and vote.count(" disabled>") == 2
    assert '<span class="ap-own">Your review</span>' in vote and "Report this review" not in vote
    other = next(r["id"] for r in a["top_reviews"][1:] if f'data-id="{r["id"]}"' in html)
    assert "Report this review" in card(html, other) and "is-own" not in card(html, other).split('class="ob-ra"', 1)[1]


def test_vote_handler_ignores_own_posts():
    js = (HERE / "shared/page.js").read_text()
    assert 'if (voteBtn.disabled || voteBtn.closest(".ob-vote.is-own")) return;' in js


# ---- 7. Edit and Delete on your own replies (D's plan rule, confirm before delete) ----

@pytest.mark.parametrize("plan,edit", [("free", False), ("trial", True), ("pro", True), ("founding", True)])
def test_own_reply_edit_by_plan_delete_for_all(tmp_path, plan, edit):
    html = render(tmp_path, threaded(), viewer={"kind": "member", "plan": plan, "name": "zz"})
    mine = reply_html(html, "m3")
    assert ('class="ob-ownact ob-redit" data-id="m3">Edit</button>' in mine) is edit
    assert 'class="ob-ownact ob-rdel" data-id="m3">Delete</button>' in mine
    for other in ("m1", "m2"):
        assert "ob-redit" not in reply_html(html, other) and "ob-rdel" not in reply_html(html, other)
    assert f'data-can-edit="{"true" if edit else "false"}" data-can-delete="true"' in html


def test_no_15_minute_window_on_replies(tmp_path):
    a = threaded()
    a["top_reviews"][0]["replies"][2]["when"] = "2025-01-01"     # long ago: D's rule still offers Edit on Pro
    html = render(tmp_path, a, viewer={"kind": "member", "plan": "pro", "name": "zz"})
    assert "ob-redit" in reply_html(html, "m3")
    assert "15 minutes" not in (HERE / "template/parts/review_replies.j2").read_text().split("-#}", 1)[1]


def test_delete_asks_remove_or_keep_first():
    js = (HERE / "shared/page.js").read_text()
    assert "Remove this reply?</span>" in js
    assert 'class="ob-ownact ob-rdel-yes">Remove</button>' in js and 'class="ob-ownact ob-rdel-no">Keep</button>' in js
    # the reply is only changed on Remove, never straight from Delete
    rdel = js.split('var rdel = e.target.closest(".ob-rdel");', 1)[1].split("var rno", 1)[0]
    assert "Reply removed" not in rdel and "remove()" not in rdel


def test_reply_posted_in_preview_gets_own_row():
    js = (HERE / "shared/page.js").read_text()
    assert "+ ownReplyRow(rid);" in js and '<span class="ap-own">Your reply</span>' in js


# ---- 9. Replies under a school's official reply; unlimited school <-> member back-and-forth ----

def official_thread():
    a = copy.deepcopy(PAID)
    rv = next(r for r in a["top_reviews"] if any(p.get("own") for p in r.get("official_replies") or []))
    off = next(p for p in rv["official_replies"] if p.get("own"))
    off["id"] = "o1"
    off["up"] = 2
    # school -> member -> school -> member -> school -> member: no cap
    chain, parent = [], None
    for i in range(6):
        school = i % 2 == 1
        node = {"id": f"t{i}", "parent_id": parent, "when": "2026-11-0%d" % (i + 1), "text": f"turn {i}"}
        node.update({"official": True, "school": "exampleflight", "paid": True} if school else {"name": f"pilot{i}"})
        chain.append(node); parent = node["id"]
    off["replies"] = chain
    return a, rv["id"]


@pytest.mark.parametrize("plan", ["free", "pro"])
def test_members_can_reply_under_official_reply(tmp_path, plan):
    a, rid = official_thread()
    html = render(tmp_path, a, viewer={"kind": "member", "plan": plan, "name": "zz"})
    c = card(html, rid)
    off = c.split('data-id="o1" data-depth="0"', 1)[1]
    assert off.split('class="ob-reply', 1)[0].count('class="ob-rreply" data-to="o1"') == 1
    assert 'data-rid="o1"' in off                       # votes on the official reply too
    assert 'data-id="t0"' in off and 'data-depth="1"' in off


def test_school_and_member_go_back_and_forth_without_a_cap(tmp_path):
    a, rid = official_thread()
    html = render(tmp_path, a, viewer={"kind": "member", "plan": "free", "name": "zz"})
    c = card(html, rid)
    for i in range(6):
        assert f'data-id="t{i}"' in c, i
        assert f'class="ob-rreply" data-to="t{i}"' in c, i    # every turn can be answered, school turns included
    school_turn = c.split('data-id="t1"', 1)[0].rsplit("<div", 1)[1]
    assert "is-official" in school_turn
    assert "exampleflight<span class=\"official-suffix\">.official</span>" in c.split('data-id="t1"', 1)[1]
    assert "Continue thread" in c                            # deep turns fold, they are not blocked
    assert "View 7 replies" in c                              # official reply + 6 turns


def test_guest_sees_official_reply_but_no_member_thread(tmp_path):
    a, rid = official_thread()
    html = render(tmp_path, a)
    c = card(html, rid)
    assert "Thank you" in c or 'data-id="o1"' in c
    assert 'data-id="t0"' not in c and "ob-rreply" not in c and 'data-rid="o1"' not in c


def test_page_js_nests_a_reply_under_depth_zero_official_reply():
    js = (HERE / "shared/page.js").read_text()
    assert "var depth = +(parent.getAttribute(\"data-depth\") || 1);" in js


# ---- 10. Premium extras + status banners (design pending, hidden, sample data) ----

def build_pv(tmp_path, ato, name, **kw):
    d = tmp_path / ("d-" + name); d.mkdir()
    (d / "a.json").write_text(json.dumps(ato))
    generator.build(d, tmp_path / name, "amethyst", TODAY, **kw)
    return (tmp_path / name / ato["slug"] / "index.html").read_text()


def test_default_build_has_no_premium_or_banners(tmp_path):
    for status in ("paid", "lapsed", "verified"):
        a = copy.deepcopy(PAID); a["status"] = status
        html = build_pv(tmp_path, a, status)
        assert "pr-premium" not in html and "pr-banner" not in html and "SAMPLE" not in html


def test_unlocked_extras_are_hidden_sample_blocks(tmp_path):
    html = build_pv(tmp_path, copy.deepcopy(PAID), "on", premium_preview=True, premium_days_paid=45)
    sec = html.split('<section class="ob-sec pr-premium"', 1)[1].split("</section>", 1)[0]
    assert 'data-design-pending="premium-extras" hidden>' in sec
    for t in ("Fleet", "Announcements", "Course prices", "Jobs"):
        assert f"<h3>{t}</h3>" in sec
    assert "SAMPLE extras · design pending" in sec


def test_extras_locked_before_30_days_and_for_unpaid(tmp_path):
    a = copy.deepcopy(PAID)
    html = build_pv(tmp_path, a, "early", premium_preview=True, premium_days_paid=29,
                    viewer={"kind": "member", "plan": "school", "role": "owner"})
    assert "These extras stay private" in html and "<h3>Fleet</h3>" not in html
    assert "Premium extras still locked" in html
    assert generator.premium_model(False, 400)["unlocked"] is False
    assert generator.premium_model(True, 30)["unlocked"] is True


@pytest.mark.parametrize("status,viewer,title", [
    ("lapsed", None, "Premium has ended"),
    ("verified", None, "Claimed · no Premium yet"),
    ("paid", {"kind": "member", "plan": "school", "role": "owner"}, "Premium extras unlocked"),
    ("paid", {"kind": "member", "plan": "pro", "role": "admin"}, "Super Admin"),
])
def test_status_banners_hidden_by_default(tmp_path, status, viewer, title):
    a = copy.deepcopy(PAID); a["status"] = status
    html = build_pv(tmp_path, a, "b", premium_preview=True, premium_days_paid=45, viewer=viewer)
    banner = html.split(f"<h2>{title}</h2>", 1)[0].rsplit("<aside", 1)[1]
    assert 'data-design-pending="status-banner" hidden>' in banner


def test_premium_uses_only_option_d_tokens_and_is_marked_design_pending():
    css = (HERE / "shared/page.css").read_text().split("DESIGN PENDING (ATO-11)", 1)[1]
    import re
    assert not re.search(r"#[0-9a-fA-F]{3,6}\b|rgba?\(", css)
    for f in ("premium.j2", "status_banners.j2"):
        assert "DESIGN PENDING" in (HERE / "template/parts" / f).read_text()
    js = (HERE / "shared/page.js").read_text()
    assert 'get("preview-premium") !== "1"' in js
