"""One test (or more) for every bug fixed on 11 Nov 2026. Run with  python3 -m pytest -q  from ato-generator/."""
import copy, json, re, sys, datetime as dt
from fractions import Fraction
from pathlib import Path
import pytest

HERE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(HERE))
import generator, rating, rules  # noqa: E402

TODAY = dt.date(2026, 11, 9)
PAID = json.loads((HERE / "data/ato/example-flight-academy.json").read_text())
UNPAID = json.loads((HERE / "data/ato/example-air-school.json").read_text())


def render(tmp_path, ato, **kw):
    d = tmp_path / "data"; d.mkdir(exist_ok=True)
    (d / "a.json").write_text(json.dumps(ato))
    generator.build(d, tmp_path / "out", "amethyst", kw.pop("today", TODAY), **kw)
    return (tmp_path / "out" / ato["slug"] / "index.html").read_text()


def card(html):
    return html.split('<div class="ob-ratebanner">', 1)[1].split('<div class="ob-list-r">', 1)[0]


# ---- Bug 1: bars and counts come from the rating summary, not from the reviews printed on the page ----
def test_bars_and_counts_come_from_the_summary_not_from_the_top_reviews(tmp_path):
    h = card(render(tmp_path, copy.deepcopy(PAID)))                # the page prints 3 reviews; the school has 9 ratings
    assert re.findall(r'<div class="ob-bar"><span>(\d)</span>.*?<b>(\d+)</b></div>', h) == [("5", "4"), ("4", "4"), ("3", "1"), ("2", "0"), ("1", "0")]
    assert re.findall(r'<span class="ob-ratechip"><b>([^<]+)</b> ([^<]+)</span>', h) == [("9", "Reviews"), ("8", "Written reviews"), ("8", "Rated 4.0+"), ("2", "Certificates")]
    assert "scaleX(0.4444" in h                                     # 4 of 9, not 1 of 3


def test_a_summary_that_does_not_add_up_stops_the_build():
    a = copy.deepcopy(PAID); a["rating"]["bars"][0]["count"] = 7
    with pytest.raises(ValueError, match="bars must add up"):
        generator.check(a)
    b = copy.deepcopy(PAID); b["rating"] = {"count": 28, "avg_overall": 4.3}      # the old shape: an average with a count
    with pytest.raises(ValueError, match="must be the server summary"):
        generator.check(b)
    c = copy.deepcopy(PAID); c["rating"]["written"] = -1
    with pytest.raises(ValueError, match="written count"):
        generator.check(c)


# ---- Bug 2: one stated rounding rule ----
@pytest.mark.parametrize("overall,bar", [("9/2", 5), ("7/2", 4), ("5/2", 3), ("3/2", 2), ("349/100", 3), ("13/3", 4), ("1", 1), ("5", 5)])
def test_bar_is_the_overall_rounded_half_up(overall, bar):
    assert rating.bar_of(Fraction(overall)) == bar                  # round() would give 4.5 -> 4 and 2.5 -> 2


def test_display_rounding_is_half_up_and_exact():
    assert [rating.display1(17, 4), rating.display1(13, 3), rating.display1(79, 20), rating.display1(789, 200)] == ["4.3", "4.3", "4.0", "3.9"]


def test_summary_mirror_matches_the_server_rules():
    old = "2026-01-01"
    rows = [{"stars": {"org": 4}, "text": "x", "account_created": old} for _ in range(24)] + [{"stars": {"org": 3}, "text": "", "account_created": old}]
    s = rating.summarise(rows, TODAY, certificates=2)
    assert (s["score"], s["gold"], s["count"], s["written"], s["rated_hi"]) == ("4.0", False, 25, 24, 24)   # raw 3.96: not gold (NEW-01)
    assert [b["count"] for b in s["bars"]] == [0, 24, 1, 0, 0]
    assert generator.check({**copy.deepcopy(PAID), "rating": s}) is not None      # the mirror's output is a valid summary
    mixed = [{"stars": {"org": 5, "flt": 5, "gnd": 5, "ins": 5, "saf": 5, "val": 5, "avl": 5}, "text": "a", "account_created": old},
             {"stars": {"org": 1}, "text": "b", "account_created": old},
             {"stars": {"org": 5, "flt": 5, "gnd": 5, "ins": 5, "saf": 5, "val": 5, "avl": 5}, "status": "deleted", "text": "c", "account_created": old},
             {"stars": {"org": 1}, "status": "spam_held", "text": "d", "account_created": old}]
    assert rating.summarise(mixed, TODAY)["score"] == "3.7"                         # decision D1: average of review overalls
    assert rating.summarise(mixed, TODAY, mode="every_star")["score"] == "4.7"      # ... or of every star
    assert rating.summarise(mixed, TODAY)["written"] == 2                           # the deleted one counts, but is not "written"
    cats = {c["key"]: c for c in rating.summarise(mixed, TODAY)["categories"]}
    assert cats["org"]["score"] == "3.7" and cats["flt"]["score"] is None           # Fleet has only 2 ratings (REV-011)


# ---- Bug 3: no frozen default date ----
def test_today_defaults_to_today_in_south_africa(tmp_path, monkeypatch):
    monkeypatch.setattr(generator, "today_sast", lambda: dt.date(2030, 1, 2))
    generator.main(["--data", str(HERE / "data/ato"), "--out", str(tmp_path / "o")])
    assert json.loads((tmp_path / "o" / "manifest.json").read_text())["today"] == "2030-01-02"
    h = (tmp_path / "o" / "example-flight-academy" / "index.html").read_text()
    assert ">Current<" not in h and h.count(">Expired<") == 2      # both example certificates have ended by 2030
    assert 'data-until="2027-06-30"' in h                          # the pill carries its date for the page script


def test_sast_date_does_not_lag_behind_utc():
    assert generator.SAST.utcoffset(None) == dt.timedelta(hours=2)
    assert generator.day_ms(dt.date(2026, 11, 9)) == int(dt.datetime(2026, 11, 8, 22, 0, tzinfo=dt.timezone.utc).timestamp() * 1000)


# ---- Bug 4: "shown" is the server's decision (3 ratings from 3 aged reviewers) ----
def test_rating_stays_hidden_when_the_server_says_so_even_with_enough_reviews(tmp_path):
    a = copy.deepcopy(PAID); a["rating"] = {"shown": False, "count": 5, "written": 5}     # e.g. two of the accounts are 3 days old
    h = render(tmp_path, a)
    assert 'data-rating-kind="empty"' in h and 'class="ob-from"' not in h
    assert re.findall(r'<span class="ob-ratechip"><b>([^<]+)</b>', card(h)) == ["5", "5", "–", "2"]   # no "Rated 4.0+" number either
    assert "application/ld+json" not in h
    assert rating.summarise([{"stars": {"org": 5}, "text": "x", "account_created": d} for d in ("2026-01-01", "2026-01-01", "2026-11-06")], TODAY)["shown"] is False


def test_a_rating_can_never_show_under_three():
    a = copy.deepcopy(UNPAID); a["rating"] = {"shown": True, "count": 2, "written": 1, "score": "4.5", "gold": True, "rated_hi": 2, "bars": []}
    with pytest.raises(ValueError, match="cannot show under 3"):
        generator.check(a)


# ---- Bug 5: the sign-in gate promises only cards that exist ----
def test_gate_counts_written_reviews_only(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))                       # 9 ratings, 8 written, 3 shown
    assert "5 more reviews, and voting after you sign in" in h
    a = copy.deepcopy(PAID); a["rating"]["written"] = 3; a["visible_reviews"] = 3
    assert "Sign in to see the rest" not in render(tmp_path, a)     # nothing more to open: no gate


# ---- Bug 6 and 8: slugs ----
def test_two_files_with_one_slug_stop_the_build(tmp_path):
    d = tmp_path / "d"; d.mkdir()
    for n in ("a", "b"):
        (d / f"{n}.json").write_text(json.dumps({**copy.deepcopy(UNPAID), "id": f"EXAMPLE_{n}"}))
    with pytest.raises(ValueError, match="is used by both a.json and b.json"):
        generator.build(d, tmp_path / "out", "amethyst", TODAY)


@pytest.mark.parametrize("slug", ["../../etc", "a/b", "Upper", "two--hyphens", "-lead", "trail-", "", "static", "fonts", "x" * 81, None, 7])
def test_unsafe_or_reserved_slug_stops_the_build(slug):
    with pytest.raises(ValueError, match="slug"):
        generator.check({**copy.deepcopy(UNPAID), "slug": slug})


# ---- Bug 9: contact details ----
def test_bad_contact_values_are_left_out_and_never_become_links(tmp_path):
    a = copy.deepcopy(UNPAID)
    a["contact"] = {"phone": "call now!", "email": 'x@y.z" onclick="alert(1)', "web": "javascript:alert(1)"}
    warn = generator.check(a)
    assert a["contact"] == {"phone": None, "email": None, "web": None}
    assert sum("left out" in w for w in warn) == 3
    h = render(tmp_path, a)
    assert 'href="#"' not in h and "javascript:" not in h and "onclick" not in h
    assert h.count('<span class="ob-clink" aria-disabled="true">') == 3          # same pill, not a dead link


def test_good_contact_values_are_links(tmp_path):
    a = copy.deepcopy(UNPAID); a["contact"] = {"phone": "+27 11 555 0100", "email": "info@school.example", "web": "https://www.school.example/"}
    h = render(tmp_path, a)
    assert 'href="tel:+27115550100"' in h and 'href="mailto:info@school.example"' in h and 'href="https://www.school.example"' in h
    assert "aria-disabled" not in h


# ---- Bug 10: counted upvotes ----
def test_server_count_wins_and_builds_are_repeatable():
    old = 1767225600000
    assert generator.counted_upvotes({"up": 3, "vote_records": [{"value": 1, "accountCreated": old}] * 50}) == 3
    assert generator.counted_upvotes({"upvotes": 99}) == 0                         # a raw "upvotes" number is never trusted
    with pytest.raises(ValueError, match="needs the build date"):
        generator.counted_upvotes({"vote_records": [{"value": 1, "accountCreated": old}]})
    a, b = copy.deepcopy(PAID), copy.deepcopy(PAID)
    generator.check(a); generator.check(b)
    assert [r["id"] for r in generator.page_model(a, TODAY)["top"]] == [r["id"] for r in generator.page_model(b, TODAY)["top"]] == ["r2", "r1", "r3"]


def test_top_three_uses_the_server_count_when_given(tmp_path):
    a = copy.deepcopy(PAID)
    for r, up in zip(a["top_reviews"], (1, 2, 30, 0)):
        r.pop("vote_records", None); r["up"] = up
    ids = re.findall(r'<article class="ob-review[^"]*" data-id="([^"]+)"', render(tmp_path, a))
    assert ids == ["r3", "r2", "r1"]


# ---- Bug 11: the word "pilot" in course names is a switch (decision D4) ----
def test_pilot_in_course_names_follows_the_switch(tmp_path):
    assert "Private Licence (A)" in render(tmp_path, copy.deepcopy(PAID))                         # default: as before
    assert "Private Pilot Licence (A)" in render(tmp_path, copy.deepcopy(PAID), scrub_courses=False)


def test_courses_are_grouped_on_the_original_name(tmp_path):
    """PPL/CPL stay licences after 'pilot' is stripped; Night / Instrument / Instructor / Multi-engine are ratings."""
    paid = {g["name"]: g["items"] for g in generator.course_groups(copy.deepcopy(PAID))}
    assert paid["Licences"] == ["Private Licence (A)", "Commercial Licence (A)"]
    assert paid["Ratings"] == ["Night rating", "Instrument rating", "Instructor rating, Grade III", "Multi-engine class rating"]
    assert "Other" not in paid
    unpaid = {g["name"]: g["items"] for g in generator.course_groups(copy.deepcopy(UNPAID))}
    assert unpaid["Licences"] == ["Private Licence (A)"]
    assert unpaid["Ratings"] == ["Night rating"]
    assert "Other" not in unpaid
    kept = {g["name"]: g["items"] for g in generator.course_groups(copy.deepcopy(PAID), scrub_courses=False)}
    assert kept["Licences"] == ["Private Pilot Licence (A)", "Commercial Pilot Licence (A)"]
    h = render(tmp_path, copy.deepcopy(PAID))
    lic = re.search(r'<h3 class="ob-cr-gh">Licences</h3>.*?</ul>', h, re.S).group(0)
    rat = re.search(r'<h3 class="ob-cr-gh">Ratings</h3>.*?</ul>', h, re.S).group(0)
    assert "Private Licence (A)" in lic and "Commercial Licence (A)" in lic
    assert "Night rating" in rat and "Instrument rating" in rat
    assert "Other" not in h.split('<section class="ob-sec ob-crs">', 1)[1].split("</section>", 1)[0]


# ---- Bug 13: page head, sign-in return, API by school ----
def test_head_is_noindex_by_default_and_complete_when_indexed(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))
    assert '<meta name="robots" content="noindex,nofollow">' in h and 'rel="canonical"' not in h
    assert '<meta name="description" content="Example Flight Academy: flight training at FACT, FAGG.' in h
    h = render(tmp_path, copy.deepcopy(PAID), site="https://example.co.za", index=True)
    assert '<meta name="robots" content="index,follow">' in h
    assert '<link rel="canonical" href="https://example.co.za/ato/example-flight-academy">' in h
    ld = json.loads(re.search(r'<script type="application/ld\+json">(.*?)</script>', h, re.S).group(1))
    assert ld["aggregateRating"] == {"@type": "AggregateRating", "ratingValue": "4.3", "bestRating": "5", "worstRating": "1", "ratingCount": 9}


def test_rating_markup_cannot_be_broken_out_of(tmp_path):
    a = copy.deepcopy(PAID); a["name"] = 'Evil</script><script>alert(1)</script> & Co'
    h = render(tmp_path, a)
    assert "<script>alert(1)" not in h
    ld = json.loads(re.search(r'<script type="application/ld\+json">(.*?)</script>', h, re.S).group(1))
    assert ld["name"] == a["name"]


def test_sign_in_returns_to_the_school_and_the_api_is_by_school(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))
    assert 'href="/signin/?return=%2Fato%2Fexample-flight-academy"' in h           # UR-55
    assert 'data-api="/api/ato/example-flight-academy/view"' in h                  # the school, never a certificate number
    assert "EXAMPLE_9991_ATO/view" not in h


# ---- More: allow-list, anonymous dates, category rows ----
def test_an_unknown_field_stops_the_build():
    for path in (["member_email"], ["top_reviews", 0, "author_email"], ["top_reviews", 0, "author", "plan"], ["bases", 0, "owner"]):
        a = copy.deepcopy(PAID); o = a
        for k in path[:-1]:
            o = o[k]
        o[path[-1]] = "x"
        with pytest.raises(ValueError, match="not allowed|private field"):
            generator.check(a)


def test_sample_reviews_cannot_ride_into_real_data():
    a = copy.deepcopy(PAID); a["id"] = "SACAA/1132/ATO"; a["top_reviews"][0]["id"] = "ex11"
    with pytest.raises(ValueError, match="REV-022"):
        generator.check(a)


def test_anonymous_review_shows_the_month_only(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))
    anon = re.search(r'<article class="ob-review is-anon".*?</article>', h, re.S).group(0)
    assert "<time>Aug 2026</time>" in anon and "30 Aug" not in h and "1 Aug 2026" not in h       # REV-038: no day, real or made up
    assert "<time>2 Oct 2026</time>" in h                                                        # named reviews keep the day


def test_category_rows_only_with_the_switch(tmp_path):
    assert "ob-catavgs" not in render(tmp_path, copy.deepcopy(PAID))
    h = render(tmp_path, copy.deepcopy(PAID), show_categories=True)
    rows = re.findall(r'<div class="ob-cat( is-hi)?" data-cat="(\w+)"><span class="ob-cat-l"><span>([^<]+)</span></span>.*?<b class="ob-cat-n[^"]*">([^<]+)</b></div>', h, re.S)
    assert [(r[2], r[3]) for r in rows] == [("Organisation", "4.2"), ("Fleet", "4.3"), ("Ground school", "4.0"), ("Instructors", "4.6"),
                                            ("Safety culture", "4.6"), ("Value", "3.8"), ("Availability", "4.2")]
    assert [bool(r[0]) for r in rows] == [True, True, True, True, True, False, True]             # 3.8 is not gold
    a = copy.deepcopy(PAID); a["rating"]["categories"][1].update(score=None, gold=False, count=2)
    assert re.search(r'data-cat="flt">.*?<b class="ob-cat-n">–</b>', render(tmp_path, a, show_categories=True), re.S)   # a dash under 3 ratings
