"""Paid About and Contact (DESIGN PENDING, PREM-1; design 20 Nov 2026). Real builds never carry them; the preview flag draws
them for a paid school with SAMPLE details, and anything the school has not filled in is left out."""
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)
PAID = json.loads((HERE / "data/ato/example-flight-academy.json").read_text())
UNPAID = json.loads((HERE / "data/ato/example-air-school.json").read_text())
LAPSED = json.loads((HERE / "data/ato/example-lapsed-school.json").read_text())


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", "amethyst", TODAY, **kw)
    return (tmp_path / "out" / ato["slug"] / "index.html").read_text()


def test_real_builds_and_unpaid_schools_have_neither_block(tmp_path):
    for i, (ato, kw) in enumerate([(PAID, {}), (UNPAID, {"premium_preview": True}), (LAPSED, {"premium_preview": True})]):
        html = render(tmp_path / str(i), copy.deepcopy(ato), **kw)
        assert not re.search(r'class="(pa-|pc-)', html) and "data-premium" not in html


def test_blocks_sit_in_the_right_places_and_start_hidden(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID), premium_preview=True)
    assert html.index("pr-news") < html.index('class="pa-about"') < html.index("ob-about-sec") < html.index("pr-zone") \
        < html.index('id="pc-contact"') < html.index("ob-rateblock")
    for needle in ('class="pa-about"', 'id="pc-contact"', 'class="pc-bar is-away"'):
        assert re.search(re.escape(needle) + r'[^>]*data-design-pending="premium-extras" hidden', html)


def test_about_has_lead_two_paragraphs_facts_photo_and_says_sample(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID), premium_preview=True)
    about = html.split('class="pa-about"', 1)[1].split("</section>", 1)[0]
    assert about.count('class="pa-lead"') == 1 and about.count("<p>") == 2
    for label in ("Founded", "Home aerodrome", "Fleet", "Instructors", "Students trained"):
        assert f"<dt>{label}</dt>" in about
    assert '<a class="pa-icao" href="/ad/FACT">FACT</a>' in about            # ICAO from the first base
    assert "<dd>8<small>4 types</small></dd>" in about                       # from the fleet the school lists
    assert "<figcaption>Sample photograph." in about and "Sample details" in about
    assert "<svg" not in about and "ob-card" not in about                    # no icons, no boxes


def test_contact_rows_are_real_links_and_the_form_is_inline(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID), premium_preview=True)
    c = html.split('id="pc-contact"', 1)[1].split("</nav>", 1)[0]
    assert 'href="tel:+27000000000"' in c and 'href="mailto:contact@example.invalid"' in c and 'href="https://wa.me/27000000000"' in c
    assert "destination=Cape%20Town%20International%2C%20Cape%20Town" in c
    assert 'id="pc-ask-btn"' in c and 'aria-expanded="false"' in c and "Ask about training" in c
    form = c.split('<form class="pc-form"', 1)[1].split("</form>", 1)[0]
    assert 'name="name"' in form and 'name="email"' in form and 'name="course"' in form and 'name="message"' in form
    assert "<option>Night rating</option>" in form                            # the school's own courses
    assert "action=" not in form                                              # nothing is sent anywhere
    bar = c.split('<nav class="pc-bar', 1)[1]
    assert bar.count("<a ") == 3 and "Call" in bar and "Email" in bar and "Directions" in bar
    assert '"[[1, 2, 3, 4, 5]' not in c and "data-hours" in c and "Mon to Fri" in c and "Saturday" in c and "Sunday" in c


def test_missing_details_are_left_out_not_invented(tmp_path):
    ato = copy.deepcopy(PAID)
    ato["contact"] = {"phone": None, "email": None, "web": None}
    ato["profile"] = {"lead": "One sentence from the school."}                 # nothing else filled in
    html = render(tmp_path, ato, premium_preview=True)
    about = html.split('class="pa-about"', 1)[1].split("</section>", 1)[0]
    assert "One sentence from the school." in about and "Sample" not in about  # a real profile is not labelled sample
    for label in ("Founded", "Instructors", "Students trained"):
        assert label not in about
    assert "<dt>Home aerodrome</dt>" in about and "<figure" not in about and "pa-text" not in about
    c = html.split('id="pc-contact"', 1)[1]
    assert "pc-row" not in c and "pc-hours" not in c and "wa.me" not in c and 'class="pc-bar' in c
    assert "Sample address" not in c and "Sample details" not in c


def test_an_empty_profile_and_no_about_text_leaves_only_what_is_known(tmp_path):
    ato = copy.deepcopy(PAID)
    ato["about"] = None; ato["profile"] = {}
    about = render(tmp_path, ato, premium_preview=True).split('class="pa-about"', 1)[1].split("</section>", 1)[0]
    assert "pa-lead" not in about and "pa-text" not in about and "<figure" not in about and "Sample" not in about
    assert about.count("<dt>") == 2                                            # the home aerodrome and the fleet only


def test_without_a_school_lead_the_about_text_is_split(tmp_path):
    lead, paras = generator.sentence_split("A small school. We teach PPL. We teach night rating. We teach IR.")
    assert lead == "A small school." and len(paras) == 2 and paras[0].startswith("We teach PPL.")
    assert generator.sentence_split("Only one sentence.") == ("Only one sentence.", [])
    assert generator.sentence_split(None) == ("", [])
    ato = copy.deepcopy(PAID); ato["profile"] = {"founded": 2001}
    html = render(tmp_path, ato, premium_preview=True)
    assert 'class="pa-lead">Example text.' in html                             # the page's own About text leads


def test_days_label():
    assert generator.days_label([1, 2, 3, 4, 5]) == "Mon to Fri"
    assert generator.days_label([6]) == "Saturday" and generator.days_label([0]) == "Sunday"
    assert generator.days_label([6, 0]) == "Sat, Sun" and generator.days_label([1, 3]) == "Mon, Wed"


@pytest.mark.parametrize("bad", [
    {"surprise": 1}, {"whatsapp": "call me"}, {"whatsapp": "+27 1"}, {"founded": "2011"}, {"founded": 1800}, {"instructors": True},
    {"photo": {"url": "https://evil.example/x.jpg"}}, {"photo": {"url": "/ato/../x.jpg"}}, {"photo": {"url": "/ato/x.svg"}},
    {"photo": {"url": "/ato/x.jpg", "extra": 1}}, {"paragraphs": ["a", "b", "c"]}, {"lead": ""},
    {"hours": [{"days": [7], "open": "08:00", "close": "09:00"}]}, {"hours": [{"days": [1], "open": "17:00", "close": "08:00"}]},
    {"hours": [{"days": [1], "open": "8am", "close": "9am"}]}, {"hours": [{"days": [1], "open": "08:00", "close": "09:00", "x": 1}]},
])
def test_bad_profile_stops_the_build(tmp_path, bad):
    ato = copy.deepcopy(PAID); ato["profile"] = bad
    with pytest.raises(ValueError):
        render(tmp_path, ato, premium_preview=True)


def test_a_good_profile_is_accepted():
    generator.check_profile({"lead": "x", "paragraphs": ["a", "b"], "founded": 2011, "instructors": 3, "students_trained": 90,
                             "whatsapp": "+27 82 000 0000", "photo": {"url": "/ato/static/a.jpg", "alt": "a", "caption": "c"},
                             "hours": [{"days": [1, 2], "open": "08:00", "close": "16:00"}, {"days": [0], "closed": True}],
                             "address": "1 Sample Road"}, "x")


def test_the_word_pilot_stays_off_the_page(tmp_path):
    ato = copy.deepcopy(PAID); ato["profile"] = {"lead": "We train pilot students well.", "paragraphs": ["Every pilot flies."]}
    about = render(tmp_path, ato, premium_preview=True).split('class="pa-about"', 1)[1].split("</section>", 1)[0]
    assert "pilot" not in about.lower()
