#!/usr/bin/env python3
# linguabase-dictionary-site.py -- a dictionary & thesaurus website, one
# static page per word or phrase, built from the Linguabase release (CC0,
# linguabase.org/download.html). The same method as idea.org/words.
#
#   python3 linguabase-dictionary-site.py          build site/ (or site.zip)
#   python3 linguabase-dictionary-site.py serve    preview at localhost:8000
#
# Needs: pip install duckdb pyarrow
# Reads ten of the thirteen tables, full tier, as parquet, from TABLES
# (either TABLES/<table>.full.parquet or TABLES/<table>/<table>.full.parquet):
#   vocabulary  definitions  clues  senses  sense_associations
#   associations  word_families (core and full)  antonyms  categories
#   scores_labels
# Writes, into OUT:
#   words/<name>.html     one page per headword (US and us are two pages)
#   index.html 404.html style.css search.js
#   search/start.json search/g/<prefix>.json search/x.json   suggestions
#   sitemap-<n>.xml sitemap.xml   report.json
#
# The settings you might edit:
CAP = 500_000                       # headwords before thin entries drop out
SITE = 'https://www.example.org'    # the site's address, for canonical links
TABLES = 'tables'
OUT = 'site'

import collections, gzip, html, json, os, re, sys, unicodedata, zipfile
import urllib.parse
import duckdb, pyarrow as pa


# ---- the tables --------------------------------------------------------
def connect(tables):
    con = duckdb.connect()
    con.execute('set enable_progress_bar = false')

    def path(t, tier='full'):
        for p in (f'{tables}/{t}.{tier}.parquet',
                  f'{tables}/{t}/{t}.{tier}.parquet'):
            if os.path.exists(p):
                return p
        sys.exit(f'missing {t}.{tier}.parquet under {tables}/')
    for t in ['vocabulary', 'definitions', 'clues', 'senses',
              'associations', 'scores_labels', 'categories']:
        con.sql(f"create view {t} as select * from '{path(t)}'")
    con.sql(f"create view fam_full as select * from "
            f"'{path('word_families')}'")
    con.sql(f"create view fam_core as select * from "
            f"'{path('word_families', 'core')}'")
    for t in ['sense_associations', 'antonyms']:    # file order matters
        con.sql(f"create view {t} as select * from "
                f"read_parquet('{path(t)}', file_row_number = true)")
    return con


# ---- 1 · the headword list ---------------------------------------------
ALNUM = re.compile(r'[^\W_]')               # a letter or digit
ENTITY = re.compile(r'&#?[a-z0-9]+;')       # an HTML entity: B&amp;B


def headword_list(con, cap):
    """-> (headwords in order, the five stages as lists of (word, rank))"""
    # order: the curated core in core_rank order, then every other word
    # by familiarity_rank. The shipped files are not sorted: sort here.
    rows = con.sql("""
        select word, in_core from vocabulary
        where core_rank is not null or familiarity_rank is not null
        order by not in_core, coalesce(core_rank, familiarity_rank)
        """).fetchall()
    s1 = [(w, i + 1, c) for i, (w, c) in enumerate(rows)]
    # artifacts: no letter or digit (':)'), an HTML entity, a doubled
    # space ('neither  nor': a lost character; each has a clean twin)
    s2 = [r for r in s1 if ALNUM.search(r[0]) and not ENTITY.search(r[0])
          and '  ' not in r[0]]
    # variants: outside the core, the same letters as a core word in
    # another case -- Hey, They, Internet. (Pairs inside the core, like
    # Polish and polish, are both real words and both keep their pages.)
    core = {w.lower() for w, _, c in s2 if c}
    s3 = [r for r in s2 if r[2] or r[0].lower() not in core]
    s4 = s3[:cap]
    # thin: no paragraph and no related word on the list. Dropping one
    # can strand another, so repeat until none is left.
    keep = {w for w, _, _ in s4}
    con.register('cand', pa.table({'word': list(keep)}))
    nodef = con.sql("""
        select c.word, a.associates from cand c
        left join associations a using (word)
        anti join definitions d using (word)""").fetchall()
    while True:
        thin = {w for w, a in nodef
                if w in keep and not any(x in keep for x in a or [])}
        if not thin:
            break
        keep -= thin
    s5 = [r for r in s4 if r[0] in keep]
    stages = [[(w, r) for w, r, _ in s] for s in (s1, s2, s3, s4, s5)]
    return [w for w, _ in stages[4]], stages


# ---- page names ----------------------------------------------------------
def name(t):    # case kept; a space becomes _, a slash __ (24/7 -> 24__7)
    return unicodedata.normalize('NFC', t.replace('/', '__').replace(' ', '_'))


def href(t):    # percent-encoded the way JavaScript's encodeURIComponent is
    return '/words/' + urllib.parse.quote(name(t), safe="'-_.~!*()")


# ---- 2 · everything per word, cut to the list ------------------------------
class Data:
    pass


def load(con, words):
    D = Data()
    D.words, D.keep = words, set(words)
    D.order = {w: i + 1 for i, w in enumerate(words)}
    con.register('keep', pa.table({'word': words}))

    def rows(sql):
        return con.sql(sql).fetchall()

    def first(sql):              # one value per word: the first row wins
        out = {}
        for w, *v in rows(sql):
            out.setdefault(w, v[0] if len(v) == 1 else tuple(v))
        return out
    D.defn = first("select word, definition from definitions "
                   "join keep using (word)")
    D.clue = first("select word, clue_W3, clue_DEF from clues "
                   "join keep using (word) where meaning = 'main'")
    D.labels = first("select word, sense_labels from senses "
                     "join keep using (word)")
    fam = first("select word, relatives from fam_full join keep using (word)")
    fam.update(first("select word, relatives from fam_core "
                     "join keep using (word)"))   # the core file is cleaner
    D.fam = {w: list(dict.fromkeys(x for x in r if x in D.keep))
             for w, r in fam.items()}
    cols = ['kid_familiar', 'americana', 'geographic_english',
            'time_stability', 'concreteness', 'emotional_valence',
            'domain_specificity', 'content_rating']
    D.sl = {r[0]: dict(zip(cols, r[1:])) for r in rows(
        f"select word, {', '.join(cols)} from scores_labels "
        "join keep using (word)")}
    D.frank = first("select word, familiarity_rank from vocabulary "
                    "join keep using (word)")
    # phrases: every multi-word headword, in list order, indexed by token
    mwe = {w for (w,) in rows("select word from vocabulary "
                              "join keep using (word) where is_mwe")}
    D.mwe = [(w, w.lower()) for w in words if w in mwe]
    D.tok = collections.defaultdict(list)
    for i, (_, lt) in enumerate(D.mwe):
        for t in set(re.findall(r'\w+', lt)):
            D.tok[t].append(i)
    # categories each word belongs to, in file order
    D.cats = collections.defaultdict(list)
    for cat, game, strength, fam_s, rel_s, members in rows("""
            select category, game_suitability, category_strength,
                   familiarity, relatedness, members from categories
            where sensitivity_topic is distinct from 'offensive'
              and members <> ''"""):
        for m in set(members.split(', ')):
            if m in D.keep:
                D.cats[m].append((cat, game, strength, fam_s, rel_s))
    return D


def big_rows(con, table='keep'):
    """associations, sense rows and opposites, one row per word"""
    cur = con.execute(f"""
        with sa as (
          select word, list(struct_pack(s := sense, a := associates)
                            order by file_row_number) srows
          from sense_associations join {table} using (word)
          group by word),
        an as (
          select word, list(struct_pack(x := axis, o := opposites)
                            order by file_row_number) axes
          from antonyms join {table} using (word) group by word)
        select k.word, a.associates, sa.srows, an.axes
        from {table} k left join associations a using (word)
        left join sa using (word) left join an using (word)""")
    while True:
        batch = cur.fetchmany(2000)
        if not batch:
            return
        yield from batch


# ---- 3 · one entry ---------------------------------------------------------
STEPS = [100, 250, 500, 1000, 2000, 3000, 5000, 10000, 20000, 50000,
         100000, 200000, 500000, 1000000, 2000000]


def star(s):    # clues: trailing stars mark favorites; "n/a" means none
    return re.sub(r'\s*\bn/a$', '', re.sub(r'\s*\*+$', '', s or '').strip())


def glossed(ws, n, G):      # prefer words that have a gloss, if enough do
    g = [w for w in ws if G.get(w)]
    return (g if len(g) >= min(n, len(ws)) * 0.6 else ws)[:n]


def categories_of(W, rows, keep):
    out = []
    for cat, game, strength, fam_s, rel_s in rows:
        grade, close = {}, []
        for s, key in ((rel_s, 'rel'), (fam_s, 'fam')):
            for part in (s or '').split('; '):
                g, _, ms = part.partition('=')
                ms = ms.split(', ')
                if key == 'rel' and g == 'close':
                    close = [m for m in ms if m in keep]
                if W in ms:
                    grade[key] = g
        out.append((cat, grade.get('rel'), grade.get('fam'),
                    game or 0, strength or 0, close))
    return out


def family(W, D):
    """-> is_fam(t): t is the headword, in its family, or a phrase that
    holds one of their single words (BARK: barking, dog bark, tree bark)"""
    fam = {W.lower()} | {x.lower() for x in D.fam.get(W, [])}
    toks = sorted({x for x in fam if ' ' not in x}, key=len,
                  reverse=True) or [W.lower()]
    fam_re = re.compile(r'\b(' + '|'.join(map(re.escape, toks)) + r')\b')

    def is_fam(t):
        return t.lower() in fam or bool(fam_re.search(t.lower()))
    return is_fam, fam_re, toks


def entry(W, assoc, srows, axes, D):
    K = D.keep

    def cut(xs):    # words that have pages, in order, each once: the
        seen = set()    # association lists repeat words in a tail
        return [x for x in xs or [] if x in K
                and not (x in seen or seen.add(x))]
    rel = D.fam.get(W, [])
    is_fam, fam_re, toks = family(W, D)
    stem = re.sub(r'[^a-z]', '', W.lower())[:max(3, len(W) - 2)]

    def formy(t):
        return bool(stem) and stem in t.lower()

    # opposites: axes whose opposite sets overlap by half or more merge
    merged = []
    for a in axes or []:
        ops = [(t[:t.rfind(':')], int(t[t.rfind(':') + 1:])) for t in a['o'] or []]
        ops = [(t, r) for t, r in ops if t in K]
        if not ops:
            continue
        ts = {t for t, _ in ops}
        for m in merged:
            mt = {t for t, _ in m['ops']}
            if len(ts & mt) / min(len(ts), len(mt)) >= 0.5:
                best = dict(m['ops'])
                for t, r in ops:
                    best[t] = max(r, best.get(t, 0))
                m['ops'] = sorted(best.items(), key=lambda x: -x[1])
                break
        else:
            merged.append({'name': a['x'], 'ops': ops})
    ant = {t for m in merged for t, _ in m['ops']}

    # related words, strongest first; their positions weigh the senses
    raw = cut(assoc)
    pos = {t: i + 1 for i, t in enumerate(raw)}
    related = [t for t in raw
               if '_' not in t and not is_fam(t) and t not in ant]
    pos = {t: pos[t] for t in related}

    # senses: the curated labels, each with its own words, ordered by how
    # strongly those words lead the main list
    srow = {r['s']: cut(r['a']) for r in srows or []}
    senses = []
    for lab in D.labels.get(W) or []:
        ws = [w for w in srow.get(lab, []) if not is_fam(w)]
        if ws:
            senses.append({'label': lab.replace('_', ' '), 'words': ws,
                           'weight': sum(1 / pos[w] for w in ws if w in pos)})
    senses.sort(key=lambda s: -s['weight'])

    # phrases built on the word, one of each kind (hiking trail/trails)
    stem2 = W.lower()[:max(3, len(W) - 2)]
    ids = sorted({i for t in toks for i in D.tok.get(
        (re.findall(r'\w+', t) or [''])[0], [])})
    seen, ph, n = set(), [], 0
    for i in ids:
        t, lt = D.mwe[i]
        if t == W or not fam_re.search(lt):
            continue
        n += 1
        if n > 400:
            break
        if not any(x.startswith(stem2) for x in re.split(r'[\s-]+', lt)):
            continue
        k = ' '.join(x[:-1] if x.endswith('s') else x for x in re.sub(
            r'\b(took|taking|takes|taken)\b', 'take', lt).split(' '))
        if k not in seen:
            seen.add(k)
            ph.append(t)
    ph = ([t for t in ph if formy(t)] or ph)[:6]

    kin = [x for x in ([x for x in rel if formy(x)] or rel)
              if x.lower() != W.lower()][:9]
    cats = sorted(categories_of(W, D.cats.get(W, []), K),
                  key=lambda c: (c[1] != 'close', c[2] != 'familiar',
                                 -c[3], -c[4]))[:6]
    cats = [(c[0], [m for m in c[5] if m != W and not is_fam(m)][:5])
            for c in cats]

    # short glosses beside words, from the clues table
    need = (set(related[:40]) | set(ph) | {W}
            | {m['ops'][0][0] for m in merged[:3]}
            | {w for s in senses for w in s['words'][:30]})
    G = {}
    for w in need:
        w3, d = D.clue.get(w, (None, None))
        if star(d) or star(w3):
            G[w] = star(d) or star(w3)
    w3, d = D.clue.get(W, (None, None))

    s = D.sl.get(W, {})

    def v(k):
        x = s.get(k)
        return None if x is None or x != x else x      # NaN -> None
    badges = [b for b in [
        'Known to kids' if (v('kid_familiar') or 0) >= 4 else None,
        'Used worldwide' if (v('americana') or 0) >= 4
        and (v('geographic_english') or 0) >= 4 else
        ('Mostly American' if v('americana') and v('americana') <= 2
         else None),
        'Timeless' if (v('time_stability') or 0) >= 4 else None,
        'Concrete' if (v('concreteness') or 0) >= 4 else
        ('Abstract' if v('concreteness') and v('concreteness') <= 2
         else None),
        'Positive' if (v('emotional_valence') or 0) >= 4 else
        ('Negative' if v('emotional_valence')
         and v('emotional_valence') <= 2 else None),
        'Everyday, not technical' if (v('domain_specificity') or 0) >= 4
        else None,
        'Rated ' + v('content_rating') if v('content_rating') else None]
        if b]
    frank = D.frank.get(W) or D.order[W]
    return {
        'w': W, 'gloss': star(w3) or star(d), 'defn': D.defn.get(W) or '',
        'senses': [{'label': x['label'], 'lead': x['words'][0],
                    'glossed': glossed(x['words'][1:], 3, G),
                    'more': [w for w in x['words'][1:]
                             if w not in glossed(x['words'][1:], 3, G)][:10]}
                   for x in senses],
        'related': (glossed(related, 5, G) + [w for w in related if w not in
                    glossed(related, 5, G)][:18]) if not senses else [],
        'phrases': ph,
        'opposites': [{'axis': m['name'].lower()
                       if m['name'] == m['name'].upper() else m['name'],
                       'lead': m['ops'][0][0],
                       'more': [t for t, _ in m['ops'][1:6]]}
                      for m in merged[:3]],
        'categories': cats, 'family': kin,
        'band': next(x for x in STEPS if frank <= x), 'profile': badges,
        'rating': v('content_rating'), 'G': G}


# ---- 4 · the page ------------------------------------------------------------
def esc(s):
    return html.escape(str(s), quote=True)


def a(t, G=None):
    g = f' <span class="g">{esc(G[t])}</span>' if G and G.get(t) else ''
    return f'<a href="{href(t)}">{esc(t)}</a>{g}'


def italics(d):     # {braces} and literal <i> tags both mark italics
    h = re.sub(r'\{([^}]*)\}', r'<i>\1</i>', esc(d))
    return re.sub(r'&lt;(/?)i&gt;', r'<\1i>', h)


def first_sentence(e):
    plain = re.sub(r'<[^>]+>|[{}]', '', e['defn'])
    m = re.match(r'(.+?[.!?])\s+[A-Z]', plain)
    return (m.group(1) if m else plain) or e['gloss'] or e['w']


SEARCH = ('<form class="srch" role="search" action="/" onsubmit="return go(this)">'
          '<input name="q" type="text" inputmode="search" autocomplete="off" '
          'autocapitalize="none" spellcheck="false" placeholder="Search" '
          'aria-label="Search"><ul class="sug" hidden></ul></form>')
FOOT = ('<footer>Word data: <a href="https://www.linguabase.org">'
        'Linguabase</a> (CC0)</footer>')


def head(title, desc, canonical, extra=''):
    return (f'<!doctype html><html lang="en"><head><meta charset="utf-8">'
            f'<meta name="viewport" content="width=device-width,initial-scale=1">'
            f'<title>{esc(title)}</title><meta name="description" '
            f'content="{esc(desc)}"><link rel="canonical" href="{SITE}{canonical}">'
            f'{extra}<link rel="stylesheet" href="/style.css">'
            f'<script src="/search.js" defer></script></head>')


def sections(e):
    """the page body in parts, (part, html), in reading order"""
    G, W, out = e['G'], e['w'], []
    top = f'<h1>{esc(W)}</h1>'
    if e['gloss']:
        top += f'<p class="gloss">{esc(e["gloss"])}</p>'
    if e['defn']:
        top += f'<p class="def">{italics(e["defn"])}</p>'
    out.append(('headword', top))
    if e['phrases']:
        out.append(('phrases', '<section><h2>Phrases</h2><ul>' + ''.join(
            f'<li>{a(p, G)}</li>' for p in e['phrases']) + '</ul></section>'))
    for s in e['senses']:
        out.append(('senses', f'<section><h2>{esc(s["label"])}</h2>'
                    f'<p class="lead">{a(s["lead"], G)}</p><ul>'
                    + ''.join(f'<li>{a(w, G)}</li>' for w in s['glossed'])
                    + '</ul><p class="run">'
                    + ' · '.join(a(w) for w in s['more']) + '</p></section>'))
    if e['related']:
        out.append(('senses', '<section><h2>Related</h2><p class="run">'
                    + ' · '.join(a(w, G) for w in e['related'])
                    + '</p></section>'))
    if e['opposites']:
        out.append(('opposites', '<section><h2>Opposites</h2>' + ''.join(
            f'<p><span class="ax">{esc(m["axis"])}</span> {esc(W)} ≠ '
            f'{a(m["lead"], G)}<br>' + ' · '.join(a(t) for t in m['more'])
            + '</p>' for m in e['opposites']) + '</section>'))
    if e['categories']:
        out.append(('categories', '<section><h2>Categories</h2><ul>' + ''.join(
            f'<li><b>{esc(c)}</b> ' + ', '.join(a(m) for m in ms) + '</li>'
            for c, ms in e['categories']) + '</ul></section>'))
    if e['family']:
        out.append(('family', '<section><h2>Family</h2><p>'
                    + ', '.join(a(w) for w in e['family']) + '</p></section>'))
    out.append(('details', f'<section><h2>Details</h2><p>Familiarity: '
                f'top {e["band"]:,}' + (' · ' + ' · '.join(map(esc, e['profile']))
                                        if e['profile'] else '')
                + '</p></section>'))
    return out


def page_html(e):
    desc = first_sentence(e)
    ld = json.dumps({'@context': 'https://schema.org', '@type': 'DefinedTerm',
                     'name': e['w'], 'description': desc,
                     'url': SITE + href(e['w'])}, ensure_ascii=False)
    return (head(f'{e["w"]} — dictionary & thesaurus', desc[:160],
                 href(e['w']),
                 f'<script type="application/ld+json">{ld}</script>')
            + f'<body><header><a class="home" href="/">Dictionary</a>{SEARCH}'
            f'</header><main>' + ''.join(h for _, h in sections(e))
            + f'</main>{FOOT}</body></html>')


# ---- 5 · search suggestions --------------------------------------------------
# Suggestions are the headwords that start with what was typed, in list
# order -- the most familiar first. 1-2 letters are answered from
# start.json; each keystroke fetches the entries two letters deeper, so
# the next two keystrokes never wait. A prefix with LEAF or fewer words
# lists them all, and nothing deeper is needed. R- and X-rated words are
# suggested only once spelled out to within one letter (x.json).
TOP, LEAF = 8, 40


def fname(p):   # a-z 0-9 kept, space -> _, anything else -> -xx per byte
    return ''.join(ch if 'a' <= ch <= 'z' or '0' <= ch <= '9' else
                   '_' if ch == ' ' else
                   ''.join('-%02x' % b for b in ch.encode('utf-8'))
                   for ch in p)


def search_files(words, explicit):
    vocab = [(w.lower(), w) for w in words if w not in explicit]

    def entry_(prefix, items):
        last = len(items) <= LEAF
        e = {'w': [w for _, w in (items if last else items[:TOP])]}
        if last:
            e['last'] = 1
        else:
            x = [w for k, w in items[TOP:] if k == prefix]
            if x:
                e['x'] = x      # the prefix itself, in another case
        return e
    tree, pending = {}, [('', vocab)]
    while pending:
        prefix, items = pending.pop()
        groups = collections.defaultdict(list)
        for it in items:
            if len(it[0]) > len(prefix):
                groups[it[0][:len(prefix) + 1]].append(it)
        for c, its in groups.items():
            tree[c] = entry_(c, its)
            if 'last' not in tree[c]:
                pending.append((c, its))
    files = collections.defaultdict(dict)
    for k, e in tree.items():
        if len(k) >= 3:
            files[k[:-2]][k] = e
    for p in files:
        tree[p]['g'] = 1
    start = {'top': TOP, 'leaf': LEAF,
             'e': {k: e for k, e in tree.items() if len(k) <= 2}}
    x = collections.defaultdict(list)
    for w in words:
        if w in explicit:
            k = w.lower()
            for key in dict.fromkeys([k, k[:-1]]):
                x[key].append(w)
    return start, {fname(p): {'p': p, 'e': e} for p, e in files.items()}, x


SEARCH_JS = r'''// search.js -- suggestions as you type (linguabase-dictionary-site.py)
"use strict";
var S=null,G={},X=null;
function fname(p){var o='';for(var c of p){if(/[a-z0-9]/.test(c))o+=c;
 else if(c===' ')o+='_';else for(var b of new TextEncoder().encode(c))
 o+='-'+b.toString(16).padStart(2,'0');}return o;}
function get(u,f){fetch('/search/'+u).then(function(r){return r.ok?r.json():null;})
 .then(f,function(){f(null);});}
function name(t){return t.normalize('NFC').replace(/\//g,'__').replace(/ /g,'_');}
function href(t){return '/words/'+encodeURIComponent(name(t)).replace(/%27/g,"'");}
function ent(p){return p.length<=2?S.e[p]:(G[p.slice(0,-2)]||{})[p];}
// fetch the g files that prefix k needs, in turn (pasted input walks down);
// while typing, also k's own file, so the next two keystrokes never wait
function fill(k,ahead,done){
 for(var n=1;n<=k.length;n++){var p=k.slice(0,n),e=ent(p);
  if(!e||e.last)break;
  if(e.g&&(ahead||n<=k.length-2)){
   if(!(p in G)){G[p]=null;fetchG(p,function(){fill(k,ahead,done);});return;}
   if(G[p]===null)return;}}
 if(done)done();}
function fetchG(p,then){get('g/'+fname(p)+'.json',function(j){G[p]=j?j.e:{};then();});}
function suggest(q){var k=q.trim().toLowerCase(),w=[];if(!k||!S)return w;
 for(var n=1;n<=k.length;n++){var e=ent(k.slice(0,n));if(!e)break;w=e.w;
  if(e.last)break;if(n===k.length)w=w.concat(e.x||[]);}
 w=w.filter(function(x){return x.toLowerCase().indexOf(k)===0;});
 var same=w.filter(function(x){return x.toLowerCase()===k;});
 same.sort(function(a,b){return (b===q.trim())-(a===q.trim());});
 var out=same.concat(X&&X[k]||[],w.filter(function(x){return same.indexOf(x)<0;}));
 return out.filter(function(x,i){return out.indexOf(x)===i;}).slice(0,6);}
var F=null;
function show(){if(!F)return;var q=F.q.value,ul=F.querySelector('.sug'),s=suggest(q);
 ul.innerHTML=s.map(function(x){return '<li><a href="'+href(x)+'">'+x.replace(/&/g,'&amp;')
 .replace(/</g,'&lt;')+'</a></li>';}).join('');ul.hidden=!s.length;}
function go(f){var q=f.q.value.trim(),s=suggest(q);
 if(q)location.href=href(s.length?s[0]:q);return false;}
var started=false;
function start(then){if(started){if(then)then();return;}started=true;
 get('x.json',function(j){X=j||{};});
 get('start.json',function(j){S=j;if(then)then();show();});}
document.addEventListener('focusin',function(ev){if(ev.target.form)start();});
document.addEventListener('input',function(ev){var f=ev.target.form;
 if(!f||!f.classList.contains('srch'))return;F=f;
 var k=f.q.value.trim().toLowerCase();if(S&&k)fill(k,true,show);show();});
// 404 page: a word that differs only in case -> its page (PARIS -> Paris)
if(document.body&&document.body.dataset.missing!==undefined){
 var m=decodeURIComponent(location.pathname.replace(/^\/words\//,''))
  .replace(/__/g,'/').replace(/_/g,' ');
 document.getElementById('miss').textContent=m;
 start(function(){var k=m.toLowerCase();fill(k,false,function(){
  var hit=suggest(m).filter(function(x){return x.toLowerCase()===k;})[0];
  if(hit&&hit!==m)location.replace(href(hit));});});}
'''

STYLE = '''body{margin:0;font:18px/1.55 Georgia,serif;color:#222;background:#fff}
header{display:flex;gap:1rem;align-items:center;padding:.8rem 1rem;border-bottom:1px solid #ddd}
.home{font-weight:700;color:#57285a;text-decoration:none}
main{max-width:46rem;margin:0 auto;padding:1rem}
h1{font-size:3.2rem;line-height:1.05;margin:.6rem 0 .2rem;color:#57285a;overflow-wrap:anywhere}
.gloss{font-style:italic;color:#666;margin:0 0 1rem}
h2{font:700 .8rem/1 system-ui,sans-serif;letter-spacing:.08em;text-transform:uppercase;
 color:#8e2766;border-top:1px solid #ccc;padding-top:.8rem;margin:1.6rem 0 .5rem}
.lead{font-size:1.6rem;margin:.2rem 0}ul{padding-left:1.1rem;margin:.3rem 0}
.g{color:#666;font-style:italic;font-size:.9em}.run{color:#444}
.ax{color:#b04f00;font-variant:small-caps}a{color:inherit}
footer{max-width:46rem;margin:2rem auto;padding:0 1rem;color:#666;font-size:.85rem}
.srch{position:relative;flex:1;max-width:22rem}
.srch input{width:100%;font-size:16px;padding:.35rem .6rem;border:1px solid #bbb;border-radius:6px}
.sug{position:absolute;z-index:2;left:0;right:0;margin:2px 0 0;padding:0;list-style:none;
 background:#fff;border:1px solid #bbb;border-radius:6px}
.sug a{display:block;padding:.3rem .6rem;text-decoration:none}.sug a:hover{background:#f3e9f0}
'''


# ---- 6 · write it all ----------------------------------------------------------
class Out:
    """a folder, or a zip on disks that can't keep US and us apart"""

    def __init__(self, path):
        os.makedirs(path, exist_ok=True)
        probe = os.path.join(path, '.Case')
        open(probe, 'w').close()
        sensitive = not os.path.exists(os.path.join(path, '.case'))
        os.remove(probe)
        self.zip = None if sensitive else zipfile.ZipFile(
            path.rstrip('/') + '.zip', 'w', zipfile.ZIP_DEFLATED)
        self.path, self.bytes, self.files = path, 0, 0
        if self.zip:
            print(f'{path}/ is on a case-insensitive disk: writing '
                  f'{self.zip.filename} instead')

    def write(self, rel, text):
        data = text.encode('utf-8')
        self.bytes += len(data)
        self.files += 1
        if self.zip:
            self.zip.writestr(rel, data)
            return
        p = os.path.join(self.path, rel)
        os.makedirs(os.path.dirname(p), exist_ok=True)
        with open(p, 'wb') as f:
            f.write(data)


def main():
    con = connect(TABLES)
    words, stages = headword_list(con, CAP)
    for label, s in zip(['ordered', 'no artifacts', 'no variants',
                         f'top {CAP:,}', 'no thin entries'], stages):
        print(f'{len(s):>10,}  {label}')
    D = load(con, words)
    out = Out(OUT)
    pages = page_bytes = page_gz = 0
    for W, assoc, srows, axes in big_rows(con):
        h = page_html(entry(W, assoc, srows, axes, D))
        out.write(f'words/{name(W)}.html', h)
        pages += 1
        page_bytes += len(h.encode('utf-8'))
        page_gz += len(gzip.compress(h.encode('utf-8'), 6))
        if pages % 50_000 == 0:
            print(f'{pages:,} pages')
    explicit = {w for w, s in D.sl.items() if s['content_rating'] in ('R', 'X')}
    start, gfiles, x = search_files(words, explicit)

    def dump(o):
        return json.dumps(o, ensure_ascii=False, separators=(',', ':'))
    out.write('search/start.json', dump(start))
    out.write('search/x.json', dump(x))
    for f, o in gfiles.items():
        out.write(f'search/g/{f}.json', dump(o))
    out.write('style.css', STYLE)
    out.write('search.js', SEARCH_JS)
    out.write('index.html', head('Dictionary & thesaurus', 'Look up any word.',
                                 '/') + f'<body><main><h1>Look up any word</h1>'
              f'{SEARCH}</main>{FOOT}</body></html>')
    out.write('404.html', head('Not found', 'No page for this word.', '/404')
              + '<body data-missing><main><h1 id="miss"></h1><p>No page for '
              f'this word.</p>{SEARCH}</main>{FOOT}</body></html>')
    maps = [words[i:i + 50_000] for i in range(0, len(words), 50_000)]
    for n, chunk in enumerate(maps, 1):
        out.write(f'sitemap-{n}.xml', '<?xml version="1.0" encoding="UTF-8"?>'
                  '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
                  + ''.join(f'<url><loc>{SITE}{esc(href(w))}</loc></url>'
                            for w in chunk) + '</urlset>')
    out.write('sitemap.xml', '<?xml version="1.0" encoding="UTF-8"?>'
              '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
              + ''.join(f'<sitemap><loc>{SITE}/sitemap-{n}.xml</loc></sitemap>'
                        for n in range(1, len(maps) + 1)) + '</sitemapindex>')
    report = {'cap': CAP, 'stages': [len(s) for s in stages], 'pages': pages,
              'page_bytes': page_bytes, 'page_gzip_bytes': page_gz,
              'search_g_files': len(gfiles),
              'search_start_bytes': len(dump(start).encode('utf-8')),
              'explicit_words': len(explicit), 'files': out.files + 1,
              'bytes': out.bytes}
    out.write('report.json', json.dumps(report, indent=1))
    if out.zip:
        out.zip.close()
    print(json.dumps(report))


def serve(port=8000):           # /words/key -> words/key.html, as hosts do
    import http.server
    import functools

    class H(http.server.SimpleHTTPRequestHandler):
        def send_head(self):
            p = urllib.parse.urlsplit(self.path).path
            if p.startswith('/words/') and not p.endswith('.html'):
                self.path = p + '.html'
            if not os.path.exists(self.translate_path(self.path)):
                self.send_response(404)
                self.send_header('Content-Type', 'text/html; charset=utf-8')
                self.end_headers()
                return open(os.path.join(OUT, '404.html'), 'rb')
            return super().send_head()
    print(f'http://localhost:{port}/')
    http.server.ThreadingHTTPServer(
        ('', port), functools.partial(H, directory=OUT)).serve_forever()


if __name__ == '__main__':
    serve() if sys.argv[1:] == ['serve'] else main()
