#!/usr/bin/env python3
"""Task 15 polish tests: floating register button (FAB) + CSS game logos.

Verifies (live Flask app on :5000):
  1. FAB states on tournament detail:
     - guest            -> login FAB
     - open match       -> REGISTER FAB wired to openRulesModal()
     - not-yet-open     -> amber clock FAB
     - finished match   -> no FAB
  2. CSS game logos: glogo markup on home/tournaments/results/game/
     tournament detail + footer strip; zero <img> game artwork left.
  3. design.css ships .tdx-fab and .glogo rules.
  4. Regressions still intact: registration closes at match start.
"""
import sys
import urllib.request
import urllib.parse
import http.cookiejar
import re

BASE = "http://localhost:5000"
PASS = FAIL = 0
FAILED = []


def check(name, cond, extra=""):
    global PASS, FAIL
    if cond:
        PASS += 1
    else:
        FAIL += 1
        FAILED.append(f"{name} {extra}")
        print(f"  ✗ {name} {extra}")


def get(path, opener=None, data=None):
    url = BASE + path
    d = urllib.parse.urlencode(data).encode() if data else None
    req = urllib.request.Request(url, data=d)
    try:
        resp = opener.open(req) if opener else urllib.request.urlopen(req)
        return resp.getcode(), resp.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")


def session():
    cj = http.cookiejar.CookieJar()
    return urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))


def csrf(op, path):
    code, html = get(path, opener=op)
    m = re.search(r'name="csrf_token"[^>]*value="([^"]+)"', html)
    return m.group(1) if m else None, html


print("── 1. FAB states ──────────────────────────────────────────────")
code, html = get("/tournament/17")
check("t17 reachable", code == 200)
check("t17 guest login FAB", 'tdx-fab' in html and ('🔐' in html))
check("t17 FAB links to login", re.search(r'class="tdx-fab"[^>]*>\s*<span class="tdx-fab-icon">🔐', html) is not None)

code, html = get("/tournament/4")   # far-future upcoming, guest → login FAB
check("t4 guest login FAB", 'tdx-fab' in html and '🔐' in html)

code, html = get("/tournament/16")  # finished → no FAB
check("t16 finished → no FAB", 'tdx-fab' not in html)

# registered-user FAB (login as admin; login form has no csrf field)
op = session()
get("/auth/login", opener=op)  # seed cookies
code, body = get("/auth/login", opener=op,
                 data={"email": "admin@vapolyx.gg", "password": "Admin@123"})
code, html = get("/tournament/17", opener=op)  # admin-exception match → registration OPEN
check("logged-in REGISTER FAB shown", 'onclick="openRulesModal()"' in html and 'class="tdx-fab"' in html)
code, html = get("/tournament/8", opener=op)  # default rule, far future → amber clock FAB
check("logged-in not-yet-open amber FAB", 'tdx-fab tdx-fab-amber' in html)

print("── 2. CSS game logos everywhere ───────────────────────────────")
for path in ["/home", "/tournaments", "/results", "/game/cs2", "/tournament/16"]:
    code, html = get(path, opener=op)
    check(f"glogo on {path}", 'glogo glogo-' in html or 'glogo-hero' in html or 'glogo' in html,
          f"(code {code})")

code, html = get("/tournament/16", opener=op)
check("hero uses glogo-hero", 'glogo-hero' in html)
check("hero has game name", 'Counter-Strike 2' in html or 'VALORANT' in html or 'glogo-hero-name' in html)
check("no <img> game art on detail", 'img/games/' not in html)

code, html = get("/home", opener=op)
check("home: no img/games refs", 'img/games/' not in html)
check("home: footer strip CSS logos", 'game-logo-strip' in html and 'glogo-xs' in html)

print("── 3. CSS assets present ──────────────────────────────────────")
import pathlib
css = pathlib.Path("app/static/css/design.css").read_text(encoding="utf-8")
check(".tdx-fab rule", ".tdx-fab {" in css)
check("FAB RTL-safe inset", "inset-inline-start" in css)
check("FAB z-index 95", "z-index: 95" in css)
check("glogo base rule", ".glogo {" in css)
check("glogo 8 brand colors", all(f".glogo-{s}" in css for s in
      ["cs2", "valorant", "codm", "pubgm", "freefire", "efootball", "lol", "dota2"]))
check("glogo sizes", all(f".glogo-{z}" in css for z in ["xs", "sm", "md", "lg", "xl"]))
check("glogo-hero rule", ".glogo-hero {" in css)
check("reduced-motion guards FAB", ".tdx-fab { animation: none" in css)

print("── 4. Registration still closes at start ──────────────────────")
# match 16 started 2026-09-18 → registration must be closed server-side
code, html = get("/tournament/16", opener=op)
check("finished match shows no REGISTER", 'class="tdx-fab' not in html)

print("═" * 56)
print(f"RESULT: {PASS} passed / {FAIL} failed")
if FAILED:
    print("Failed:", *FAILED, sep="\n  - ")
sys.exit(1 if FAIL else 0)
