#!/usr/bin/env python3
"""Builds 63_eight_plus.html: every kill the coordinator has confirmed at 8+ on all four scores (the ★ rows of
_tools/8PLUS_SCOREBOARD.md), each linked straight into its weapon page's player (58k_<weapon>.html#kill=<key>).
Re-run after the scoreboard changes:  python3 _tools/make_63.py"""
import html, os, re, datetime

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SB = os.path.join(ROOT, '_tools', '8PLUS_SCOREBOARD.md')
OUT = os.path.join(ROOT, '63_eight_plus.html')
PAGE = {'speedsabre': 'sabre'}   # weapon id -> page name where they differ
WNAME = {'smg': 'SMG', 'ar': 'Assault rifle', 'sawedoff': 'Sawed-off', 'pump': 'Pump shotgun', 'flamer': 'Flamethrower',
         'hammer': 'Sledgehammer', 'minigun': 'Minigun', 'ice': 'Ice gun', 'pistol': 'Pistol', 'sniper': 'Sniper',
         'fists': 'Fists', 'beam': 'Beam', 'scythe': 'Soul scythe', 'gl': 'Grenade launcher', 'rpg': 'Rocket launcher'}

rows = []
for line in open(SB, encoding='utf-8'):
    if not line.startswith('|') or '★' not in line:
        continue
    cells = [c.strip() for c in line.strip().strip('|').split('|')]
    if len(cells) < 7 or not re.match(r'^[a-z]+\.', cells[0]):
        continue
    key_full, owner, b, c, s, a, note = cells[:7]
    key = key_full.split()[0]
    title = ' '.join(key_full.split()[1:]) or key.split('.', 1)[1].replace('mid-', '').replace('skin-', '').replace('-', ' ').upper()
    w = key.split('.')[0]
    m = re.search(r'(\d+)(?:st|nd|rd|th)', note)
    WORDS = ['FIRST','SECOND','THIRD','FOURTH','FIFTH','SIXTH','SEVENTH','EIGHTH','NINTH','TENTH','ELEVENTH','TWELFTH','THIRTEENTH','FOURTEENTH']
    mw = next((i + 1 for i, wd in enumerate(WORDS) if re.search(r'\b' + wd + r'\b', note)), None)
    rank = int(m.group(1)) if m else (mw or 999)
    kind = 'MID-ROUND' if '.mid-' in key else ('SKIN' if '.skin-' in key else 'FILM')
    rows.append(dict(key=key, title=title, w=w, owner=owner, sc=(b, c, s, a), rank=rank, kind=kind))

rows.sort(key=lambda r: (r['rank'], r['key']))
by_w = {}
for r in rows:
    by_w.setdefault(r['w'], []).append(r)

def card(r):
    page = '58k_%s.html' % PAGE.get(r['w'], r['w'])
    b, c, s, a = r['sc']
    return ('<a class="card" href="%s#kill=%s">'
            '<span class="no">#%s</span><span class="t">%s</span>'
            '<span class="k">%s · %s</span>'
            '<span class="sc"><i>B %s</i><i>C %s</i><i>S %s</i><i>D %s</i></span>'
            '<span class="go">▶ PLAY</span></a>') % (
        page, html.escape(r['key']), r['rank'] if r['rank'] < 999 else '', html.escape(r['title']),
        html.escape(WNAME.get(r['w'], r['w'])), r['kind'], b, c, s, a)

secs = []
for w in sorted(by_w, key=lambda w: (-len(by_w[w]), w)):
    secs.append('<section><h2>%s <small>%d</small></h2><div class="grid">%s</div></section>' % (
        html.escape(WNAME.get(w, w)), len(by_w[w]), ''.join(card(r) for r in by_w[w])))

now = datetime.datetime.now().strftime('%d %b %H:%M')
doc = """<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>8+ Kills</title>
<style>
:root{--bg:#0d0f1a;--card:#171a2b;--line:#2a2f4a;--ink:#f3f1ea;--dim:#9aa0bd;--gold:#f5c542;--red:#e2453c}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.4 system-ui,-apple-system,Segoe UI,sans-serif;padding:20px 16px 60px}
header{max-width:1100px;margin:0 auto 18px}h1{margin:0;font-size:28px;letter-spacing:.04em}h1 b{color:var(--gold)}
header p{color:var(--dim);margin:6px 0 0}header a{color:var(--gold)}
section{max-width:1100px;margin:22px auto 0}h2{font-size:17px;margin:0 0 10px;letter-spacing:.06em;text-transform:uppercase}h2 small{color:var(--gold);margin-left:6px}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}
.card{display:flex;flex-direction:column;gap:4px;background:var(--card);border:1px solid var(--line);border-left:4px solid var(--red);border-radius:10px;padding:12px;color:inherit;text-decoration:none;transition:transform .12s,border-color .12s}
.card:hover,.card:focus-visible{transform:translateY(-2px);border-color:var(--gold);outline:none}
.no{color:var(--gold);font-size:12px;font-weight:700}.t{font-weight:800;font-size:16px;letter-spacing:.02em}.k{color:var(--dim);font-size:12px}
.sc{display:flex;gap:6px;margin-top:4px}.sc i{font-style:normal;font-size:12px;background:#22263d;border-radius:6px;padding:2px 6px;color:var(--gold)}
.go{margin-top:6px;font-size:12px;font-weight:700;color:var(--ink);opacity:.8}
</style></head><body>
<header><h1><b>%d</b> KILLS AT 8+ ON ALL FOUR</h1>
<p>Coordinator-confirmed: Brutality, Cinematic, Script and Detail each 8 or more, scored at phone size from the built sheets. Click a kill to open it in its weapon page's player. Set the gore button (top bar) to EXTREME to see the full version. Updated %s · <a href="36_index.html">back to the index</a></p></header>
%s
</body></html>""" % (len(rows), now, '\n'.join(secs))
open(OUT, 'w', encoding='utf-8').write(doc)
print('wrote', OUT, len(rows), 'kills')
