"""ALPHA rule tests: run with  python3 -m pytest -q  (from ato-generator/)."""
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, 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())
GOLD = "#F5B83D"


@pytest.fixture(scope="module")
def pages(tmp_path_factory):
    out = tmp_path_factory.mktemp("out")
    generator.build(HERE / "data/ato", out, "amethyst", TODAY)
    return {p.parent.name: p.read_text() for p in out.glob("*/index.html")}


def hero(html):
    return html.split('<section class="ob-card ob-hero">', 1)[1].split("</section>", 1)[0]


def name_line(html):
    """The <h1> school name: the gold tick (ATO rosette, fill #F5B83D) sits here when the school is PAID."""
    return re.search(r'<h1 class="ob-name">.*?</h1>', html, re.S).group(0)


def test_gold_tick_only_for_paid(pages):
    paid, unpaid = name_line(pages["example-flight-academy"]), name_line(pages["example-air-school"])
    assert "ico-rosette" in paid and GOLD in paid                  # paid: gold tick after the name
    assert "ico-rosette" not in unpaid and GOLD not in unpaid      # verified but unpaid: no gold tick
    assert ".official" in hero(pages["example-air-school"])       # ... but the .official handle


def test_gold_tick_off_when_paid_school_stops_paying(tmp_path):
    d = tmp_path / "data"; d.mkdir()
    a = copy.deepcopy(PAID); a["status"] = "verified"
    (d / "a.json").write_text(json.dumps(a))
    generator.build(d, tmp_path / "out", "amethyst", TODAY)
    assert "ico-rosette" not in name_line((tmp_path / "out" / a["slug"] / "index.html").read_text())


def test_rating_hidden_under_3_reviews(pages):
    h = hero(pages["example-air-school"])                          # 2 reviews
    assert 'data-rating-kind="empty"' in h and 'data-v=""' in h and ">–</span>" in h
    assert "filter-glass" not in h and "out of 5 stars" not in h
    assert "rating shows at 3" in h


@pytest.mark.parametrize("score,gold,kind", [("4.3", True, "glass"), ("4.0", True, "glass"),
                                             ("4.0", False, "flat"),      # raw 3.96: shows 4.0 but is NOT gold (NEW-01)
                                             ("3.6", False, "flat")])
def test_shiny_from_4(score, gold, kind):
    a = copy.deepcopy(PAID); a["rating"].update(score=score, gold=gold)
    generator.check(a)
    m = generator.page_model(a, TODAY)
    assert m["rating_kind"] == kind and m["score"] == score


def test_shiny_page_has_sweep(pages):
    h = hero(pages["example-flight-academy"])                      # 4.3 with 9 reviews
    assert 'data-rating-kind="glass"' in h and "is-sweep" in h and "filter-glass" in h


def test_seven_categories_in_order(pages):
    want = ["Organisation", "Fleet", "Ground school", "Instructors", "Safety culture", "Value", "Availability"]   # A-30
    assert [c[1] for c in generator.CATEGORIES] == want
    # Per-review category rows are never on the guest page (REV-059).
    assert not re.findall(r'<span>\d · ([^<]+)</span>', pages["example-flight-academy"])


def test_guest_top_three_ties_newest(pages):
    ids = re.findall(r'<article class="ob-review[^"]*" data-id="(\w+)"', pages["example-flight-academy"])
    assert ids == ["r2", "r1", "r3"]                               # r2 and r1 both 14 upvotes: newer first, then r3


def test_anonymous_has_no_name_or_badges():
    a = copy.deepcopy(PAID)
    a["top_reviews"] = [{"id": "x", "author": {"anonymous": True, "name": "CANARY_NAME", "badges": ["dfe"], "licences": ["CPL"]},
                         "stars": 4.0, "upvotes": 99, "published_at": "2026-11-10",
                         "text": "Anonymous write-up for the guest page.",
                         "cost": 350000, "when": "2025-06", "licence": "CPL"}]
    m = generator.page_model(a, TODAY)
    assert m["top"][0]["author"] == {"anonymous": True, "name": "", "badges": [], "licences": []}
    rv = m["top"][0]
    assert "cost" not in rv and "when" not in rv and "licence" not in rv
    assert rv["published_at"] == "2026-11-01"


def test_certificate_current_and_expired(pages):
    h = pages["example-flight-academy"]
    assert ">Current<" in h and ">Expired<" in h


def test_no_viewer_data_in_static_page(pages):
    h = pages["example-flight-academy"]
    assert "Write a review" not in h and "ap-up" not in h
    assert "data-viewer-slot" not in h
    assert 'id="ato-topbar"' in h and "/ato/_shared/topbar.js" in h
    assert 'class="ob-top"' not in h and "logo-mark" not in h


def test_count_beside_number_and_cert_updated(pages):
    h = pages["example-flight-academy"]
    assert '<p class="ob-from"><b>4.3</b> from 9 reviews</p>' in h
    assert "Updated 1 Nov 2026" in h
    assert 'class="ob-from"' not in pages["example-air-school"]     # under 3 reviews: no score, no "from N"


def test_edited_tag(pages):
    assert pages["example-flight-academy"].count('class="ob-edtag"') == 1


def test_courses_for_guests_right_after_ratings(pages):
    for slug, h in pages.items():                                   # the static page IS the guest view
        heads = re.findall(r'<h2 class="ob-h">([^<]+)</h2>', h)
        assert heads == ["Bases and certificates", "About the ATO", "Courses", "Reviews"], (slug, heads)
        sec = h.split('<h2 class="ob-h">Courses</h2>', 1)[1].split("</section>", 1)[0]
        assert "ob-cr-pill" in sec and "data-viewer-slot" not in sec     # real course names in the page, not a signed-in slot


def test_guest_top_skips_deleted_even_if_most_upvoted(pages):
    h = pages["example-flight-academy"]
    assert "CANARY_DELETED_TEXT" not in h
    assert 'data-id="r-deleted"' not in h
    ids = re.findall(r'<article class="ob-review[^"]*" data-id="([^"]+)"', h)
    assert ids == ["r2", "r1", "r3"]


def test_deleted_stars_still_count_in_generator():
    reviews = [
        {"id": "a", "stars": 5, "status": "published", "upvotes": 1, "published_at": "2026-01-01", "text": "A"},
        {"id": "b", "stars": 3, "status": "published", "upvotes": 1, "published_at": "2026-01-02", "text": "B"},
        {"id": "c", "stars": 4, "status": "deleted", "upvotes": 99, "published_at": "2026-01-03", "text": "SECRET"},
        {"id": "h", "stars": 1, "status": "spam-held", "upvotes": 50, "published_at": "2026-01-04", "text": "HELD"},
    ]
    assert [r["id"] for r in generator.guest_top_reviews(reviews)] == ["b", "a"]
    counted = [r for r in reviews if generator.counts_toward_rating(r)]
    assert [r["id"] for r in counted] == ["a", "b", "c"]
    avg = round(sum(r["stars"] for r in counted) / len(counted), 1)
    assert avg == 4.0

def test_guest_top_counts_only_aged_upvotes():
    old = 1767225600000  # 2026-01-01
    young = int(dt.datetime(2026, 11, 8, tzinfo=dt.timezone.utc).timestamp() * 1000)
    now = int(dt.datetime(2026, 11, 9, tzinfo=dt.timezone.utc).timestamp() * 1000)
    reviews = [
        {"id": "down", "text": "D", "published_at": "2026-11-08", "status": "published",
         "vote_records": [{"value": -1, "accountCreated": old}, {"value": 0, "accountCreated": old}, {"value": 1, "accountCreated": young}]},
        {"id": "up", "text": "U", "published_at": "2026-01-01", "status": "published",
         "vote_records": [{"value": 1, "accountCreated": old}]},
    ]
    assert [r["id"] for r in generator.guest_top_reviews(reviews, now_ms=now)] == ["up", "down"]


def test_school_with_no_reviews_is_allowed():
    a = {"id": "X", "slug": "no-reviews", "name": "No Reviews", "bases": [{"ident": "FACT", "name": "Cape Town", "town": "Cape Town", "href": "/ad/FACT"}]}
    assert generator.check(a) == []
    m = generator.page_model(a, TODAY)
    assert m["rating_shown"] is False and m["top"] == [] and m["paid"] is False


def test_gifted_gets_gold_tick(tmp_path):
    d = tmp_path / "data"; d.mkdir()
    a = copy.deepcopy(PAID); a["status"] = "gifted"
    (d / "a.json").write_text(json.dumps(a))
    generator.build(d, tmp_path / "out", "amethyst", TODAY)
    assert "ico-rosette" in name_line((tmp_path / "out" / a["slug"] / "index.html").read_text())


def test_missing_code_is_flagged_and_known_code_must_link():
    warn = generator.check({
        "id": "X", "slug": "x", "name": "X",
        "bases": [{"ident": None, "name": "Port Alfred", "town": "Port Alfred", "href": None}]
    })
    assert any("missing aerodrome code" in w for w in warn)
    with pytest.raises(ValueError, match="must link to /ad/FACT"):
        generator.check({
            "id": "Y", "slug": "y", "name": "Y",
            "bases": [{"ident": "FACT", "name": "Cape Town", "town": "Cape Town", "href": "/aerodromes/fact/"}]
        })


def test_master_convert_links_and_no_invented_status():
    import master_convert
    school = {
        "school_id": "aeronav-academy",
        "slug": "skyhawk-aviation",
        "official_name": "Skyhawk Aviation (Pty) Ltd",
        "trading_name": "Skyhawk Aviation",
        "other_names": ["Aeronav Academy", "Excellentia Airline Academy"],
        "handle": None,
        "approvals": [
            {"approval_id": "SACAA/1110/ATO", "status": "Valid", "expiry": "2028-01-01",
             "current": False, "base": {"ident": "FALA", "name": "Lanseria", "town": "Johannesburg", "anchor": "fala", "href": "/aerodromes/fala/"}}
        ],
        "about": {"text": "Example about."},
        "courses": [{"name": "PPL (A)"}],
    }
    rec = master_convert.convert_school(school, TODAY)
    assert rec["slug"] == "aeronav-academy"
    assert rec["bases"][0]["href"] == "/ad/FALA"
    assert rec["bases"][0]["certificate"]["current"] is True
    assert "status" not in rec
    assert rec["top_reviews"] == []
    nameless = {
        "school_id": "unknown",
        "slug": None,
        "official_name": "",
        "trading_name": "",
        "other_names": [],
        "approvals": [{"approval_id": "SACAA/1132/ATO", "status": "Valid", "expiry": "2020-01-01",
                       "current": True, "base": {"ident": None, "name": None, "town": "Somewhere", "href": None}}],
    }
    rec2 = master_convert.convert_school(nameless, TODAY)
    assert rec2["slug"] == "1132"
    assert rec2["bases"][0]["href"] is None
    assert rec2["bases"][0]["certificate"]["current"] is False
    assert any("missing aerodrome code" in w for w in rec2["_warnings"])



def test_shared_topbar_not_copied(pages):
    for slug, h in pages.items():
        assert 'id="ato-topbar"' in h, slug
        assert "/ato/_shared/topbar.js" in h, slug
        assert 'class="ob-top"' not in h, slug
        assert "logo-mark" not in h, slug


def test_guest_page_has_rating_card_not_seven_rows(pages):
    h = pages["example-flight-academy"]
    assert "ob-ratewide" in h and "ob-ratechips" in h
    assert "ob-catavgs" not in h                 # the category rows are only drawn with --show-categories
