"""Optional write-review facts (MT, 20 Nov): courses (one or more, from the school's own list), when they trained
(From and To, or Still training) and the amount paid in rand (`cost`). REV-038 already names `cost` and `when`; the older
single `course` and `when` still read. Run from ato-generator/ with python3 -m pytest -q."""
import copy, json, re, sys, datetime as dt
from pathlib import Path
import pytest

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

TODAY = dt.date(2026, 11, 20)
BASE = json.loads((HERE / "data/ato/example-air-school.json").read_text())
CSS = (HERE / "shared/page.css").read_text()
JS = (HERE / "shared/page.js").read_text()
PREVIEW = (HERE / "preview-only/preview-switch.js").read_text()
NB = "\u00a0"


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


def with_review(**fields):
    a = copy.deepcopy(BASE)
    for rv in a["top_reviews"]:
        for k in generator.EXTRA_KEYS:
            rv.pop(k, None)
    a["top_reviews"][0].update(fields)
    return a


def line(html, rid="s1"):
    art = html.split(f'data-id="{rid}"', 1)[1].split("</article>", 1)[0]
    m = re.search(r'<p class="ob-rextra">(.*?)</p>', art)
    return m and re.sub(r"<[^>]+>", "", m.group(1)).replace(NB, " ")


def template(html):
    return re.search(r'<template id="ob-review-fields">(.*?)</template>', html, re.S).group(1)


def test_field_names():
    assert {"cost", "when", "course", "courses", "trained_from", "trained_to", "still_training"} <= generator.REVIEW_KEYS


def test_the_full_line_reads_courses_period_and_rand(tmp_path):
    h = render(tmp_path, with_review(courses=["PPL (A)", "Night rating"], trained_from="2025-03", trained_to="2026-01", cost=95000))
    assert line(h) == "Courses: PPL (A), Night rating · Trained: Mar 2025 – Jan 2026 · Paid: R 95,000"
    assert f"R{NB}95,000" in h and f"Mar{NB}2025{NB}\u2013 Jan{NB}2026" in h        # never breaks inside a month or amount


def test_still_training_reads_present(tmp_path):
    h = render(tmp_path, with_review(courses=["PPL (A)"], trained_from="2025-03", still_training=True))
    assert line(h) == "Course: PPL (A) · Trained: Mar 2025 – present"


def test_one_month_when_from_and_to_match_and_the_old_single_fields_still_read(tmp_path):
    assert line(render(tmp_path, with_review(trained_from="2025-12", trained_to="2025-12"))) == "Trained: Dec 2025"
    assert line(render(tmp_path / "old", with_review(course="PPL (A)", when="2026-03"))) == "Course: PPL (A) · Trained: Mar 2026"


def test_only_what_was_filled_in_shows(tmp_path):
    assert line(render(tmp_path, with_review(cost=1250))) == "Paid: R 1,250"
    assert line(render(tmp_path / "b", with_review(courses=["Night rating"], cost=0))) == "Course: Night rating · Paid: R 0"


def test_empty_values_stay_off_the_review(tmp_path):
    h = render(tmp_path, with_review(courses=[], trained_from="", trained_to="", cost=None))
    assert line(h) is None
    assert 'class="ob-rextra"' not in h.split('<div class="ob-list-r">', 1)[1]


def test_rand_uses_a_comma_every_three_digits():
    assert generator.review_extras({"cost": 9999999})[0]["text"] == f"R{NB}9,999,999"
    assert generator.review_extras({"cost": 95000.4})[0]["text"] == f"R{NB}95,000"


def test_pilot_is_dropped_from_course_names_like_the_courses_card(tmp_path):
    h = render(tmp_path, with_review(courses=["Private Pilot Licence (A)", "Night rating"]))
    assert line(h) == "Courses: Private Licence (A), Night rating"
    assert line(render(tmp_path / "keep", with_review(courses=["Private Pilot Licence (A)"]), scrub_courses=False)) == "Course: Private Pilot Licence (A)"


def test_duplicate_courses_count_once():
    assert generator.clean_extras({"courses": ["PPL (A)", "ppl (a) ", "IR"]})["courses"] == ["PPL (A)", "IR"]


def test_anonymous_reviews_never_show_them(tmp_path):                           # REV-038
    a = with_review(courses=["PPL (A)"], trained_from="2025-03", still_training=True, cost=95000)
    a["top_reviews"][0]["author"] = {"anonymous": True}
    h = render(tmp_path, a)
    art = h.split('data-id="s1"', 1)[1].split("</article>", 1)[0]
    assert "ob-rextra" not in art and "95,000" not in art and "present" not in art and "PPL" not in art
    rv = generator.page_model(copy.deepcopy(a), TODAY)["top"][0]
    assert rv["extras"] == [] and not set(generator.EXTRA_KEYS) & rv.keys()


@pytest.mark.parametrize("bad", [
    {"cost": -1}, {"cost": 10_000_000}, {"cost": True}, {"cost": "95000"}, {"cost": float("nan")},
    {"trained_from": "2026-13", "trained_to": "2026-13"}, {"trained_from": "2026-3", "still_training": True},
    {"trained_from": "March 2026", "still_training": True}, {"when": "2026-03-01"}, {"when": 202603},
    {"trained_from": "2025-05"},                                              # needs To or Still
    {"trained_to": "2025-05"}, {"still_training": True},                     # needs From
    {"trained_from": "2025-05", "trained_to": "2025-04"},                     # To before From
    {"trained_from": "2025-05", "trained_to": "2025-06", "still_training": True},
    {"trained_from": "2025-05", "still_training": "yes"},
    {"courses": ["x" * 81]}, {"courses": [5]}, {"courses": ["   "]}, {"courses": "PPL"},
    {"courses": ["A", "B", "C", "D", "E", "F", "G"]},                         # at most six
])
def test_a_malformed_value_stops_the_build(bad):
    with pytest.raises(ValueError):
        generator.check(with_review(**bad))


def test_a_future_month_stops_the_build(tmp_path):
    with pytest.raises(ValueError):
        render(tmp_path, with_review(trained_from="2026-12", still_training=True))
    with pytest.raises(ValueError):
        render(tmp_path / "b", with_review(trained_from="2026-10", trained_to="2027-01"))
    assert line(render(tmp_path / "c", with_review(trained_from="2026-11", still_training=True))) == "Trained: Nov 2026 – present"


def test_the_form_ships_as_an_inert_template_with_the_schools_own_courses_grouped(tmp_path):
    h = render(tmp_path, copy.deepcopy(BASE))
    t = template(h)
    model = generator.page_model(copy.deepcopy(BASE), TODAY)
    expected = [n for g in model["course_groups"] for n in g["items"]]
    assert re.findall(r'<input type="checkbox" name="courses" value="([^"]*)">', t) == expected and len(expected) >= 2
    assert [g["name"] for g in model["course_groups"]] == re.findall(r'class="ob-cpick-gh" aria-hidden="true">([^<]+)<', t)
    for needle in ('name="trained_from"', 'name="trained_to"', 'name="still_training"', 'role="switch"', 'name="cost"',
                   'data-cal="month"', 'inputmode="numeric"', '>Amount paid<', '>From<', '>To<', 'Still training here', 'data-max="6"'):
        assert needle in t, needle
    assert "Month trained" not in t and "<select" not in t
    assert t.count("(optional)") == 1 and "<form" not in t                      # one quiet heading; nothing is sent from here
    assert "<template" not in h.split("</template>", 1)[1]                      # only one copy


def test_search_shows_only_for_a_long_course_list(tmp_path):
    assert "ob-cpick-q" not in template(render(tmp_path, copy.deepcopy(BASE)))
    a = copy.deepcopy(BASE); a["courses"] = [f"Type rating {i}" for i in range(12)]
    assert 'class="ob-cpick-q"' in template(render(tmp_path / "long", a))


def test_course_names_are_escaped_in_the_template(tmp_path):
    a = copy.deepcopy(BASE); a["courses"] = ['Night <b>rating</b> & "IR"']
    t = template(render(tmp_path, a))
    assert "<b>" not in t and "&lt;b&gt;" in t and "&amp;" in t


def test_no_course_field_when_the_school_lists_no_courses(tmp_path):
    a = copy.deepcopy(BASE); a["courses"] = []
    t = template(render(tmp_path, a))
    assert 'name="courses"' not in t and 'name="trained_from"' in t and 'name="cost"' in t


def test_guest_page_shows_no_form_and_loads_no_new_files(tmp_path):
    h = render(tmp_path, copy.deepcopy(BASE))
    assert re.findall(r'<(?:script|link)[^>]+(?:src|href)="([^"]+)"', h).count("/ato/_shared/page.css") == 1
    assert "/ato/_shared/page.js" in h


def test_css_is_clean_and_uses_mono_tabular_numerals_for_rand():
    mine = CSS.split("Designer additions (20 Nov 2026)", 1)[1]
    assert "!important" not in mine
    for sel in (".ob-xfields .ob-rand input{", ".ob-rextra .ob-rx-cost{", ".ob-cpick-count{"):
        rule = mine.split(sel, 1)[1].split("}", 1)[0]
        assert "'JetBrains Mono'" in rule, sel
    assert "tabular-nums" in mine.split(".ob-xfields .ob-rand input{", 1)[1].split("}", 1)[0]
    assert 'html[data-theme="night"] .ob-xfields' in mine and 'html[data-theme="day"] .ob-xfields' in mine
    assert "prefers-reduced-motion" in mine


def test_js_rules_for_amount_period_and_courses():
    assert 'matches(".ob-rand input")' in JS and "slice(0, 7)" in JS
    assert 'tCal.setAttribute("data-min", from.value || "1950-01")' in JS and "to.disabled = on; tBtn.disabled = on;" in JS
    assert "to.value < from.value" in JS and "from.value > now" in JS
    assert "on.length >= max" in JS and "!box.checked" in JS


def test_preview_form_clones_the_template_and_its_example_card_shows_the_line():
    assert 'getElementById("ob-review-fields")' in PREVIEW
    assert "R\\u00a095,000" in PREVIEW and "ob-rextra" in PREVIEW and "present" in PREVIEW


def test_our_own_month_picker_never_the_browsers():
    """MT, 20 Nov: no native date or month inputs anywhere; our picker in SA order with figures in JetBrains Mono."""
    import re
    from pathlib import Path
    root = Path(__file__).resolve().parents[1]
    for f in list((root / "template").rglob("*.j2")) + [root / "shared/page.js", root / "preview-only/preview-switch.js"]:
        t = f.read_text()
        assert not re.search(r'type="(date|month|time|datetime-local|week)"', t), f
        assert "calendar-picker-indicator" not in t, f
    rf = (root / "template/parts/review_fields.j2").read_text()
    assert rf.count('class="ob-mo ') == 2 and rf.count('data-cal="month"') == 2 and 'data-max="now"' in rf and "data-cal-row" in rf
    assert 'type="hidden" id="wr-from" name="trained_from"' in rf and 'type="hidden" id="wr-to" name="trained_to"' in rf
    assert 'MON = ["Jan", "Feb", "Mar"' in JS and "gaToday" in JS and 'dispatchEvent(new Event("change", { bubbles: true }))' in JS
    assert '"preview-now"' in JS and "Africa/Johannesburg" not in JS.split("function gaToday", 1)[1].split("}", 1)[0]
    css = (root / "shared/page.css").read_text()
    for sel in (".ga-cal-c{", ".ga-n{"):
        assert "'JetBrains Mono'" in css.split(sel, 1)[1].split("}", 1)[0], sel
    assert "!important" not in css.split("/* Our own month and day picker", 1)[1].split("/* When you trained", 1)[0]
