#!/usr/bin/env python3
"""Build the static briggs-v-airlines site from data/matrix.json into site/.

Plain HTML/CSS/JS, no framework, mobile-friendly, Arial/system sans, no emojis.
Outputs site/index.html (matrix + filters), site/bags/<handle>.html (per-bag pages),
site/data.js (JSON payload for the client-side detail panel).
"""
import html
import json
import re
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
SITE = ROOT / "site"

STATUS_LABEL = {
    "fits": "Fits",
    "fits_unexpanded_only": "Unexpanded only",
    "does_not_fit": "Doesn't fit",
    "unknown": "Unknown",
}
STATUS_CLASS = {
    "fits": "ok",
    "fits_unexpanded_only": "warn",
    "does_not_fit": "no",
    "unknown": "unk",
}

CSS = """
:root { --ok:#1a7f37; --warn:#9a6700; --no:#cf222e; --unk:#6e7781; --line:#d0d7de; --bg:#ffffff; --fg:#1f2328; --muted:#57606a; --head:#f6f8fa; }
* { box-sizing: border-box; }
body { margin:0; font-family: Arial, Helvetica, sans-serif; color:var(--fg); background:var(--bg); font-size:15px; line-height:1.45; }
header { padding:8px 16px 4px; border-bottom:1px solid var(--line); }
h1 { font-size:16px; margin:0 0 2px; }
h1 a { color:inherit; text-decoration:none; }
h2 { font-size:15px; margin:14px 0 6px; }
header .meta { margin:0; }
.disclaimer { background:var(--head); border:1px solid var(--line); border-radius:6px; padding:6px 10px; font-size:12px; color:var(--muted); margin:6px 16px; }
.meta { font-size:12px; color:var(--muted); margin:3px 0; }
.filters { display:flex; flex-wrap:wrap; gap:10px; align-items:end; padding:10px 20px; border-bottom:1px solid var(--line); background:var(--head); }
.filters label { font-size:12px; color:var(--muted); display:block; }
.filters select { font-size:14px; padding:5px 8px; max-width:260px; }
.airpicker { padding:8px 20px; border-bottom:1px solid var(--line); background:#fff; }
.airpicker .head { display:flex; gap:12px; align-items:center; flex-wrap:wrap; margin-bottom:6px; }
.airpicker .head strong { font-size:13px; }
.airpicker .head button { font-size:12px; padding:2px 8px; cursor:pointer; }
.airchecks { column-width:160px; column-gap:16px; font-size:12px; }
.airchecks label { display:block; padding:1px 0; break-inside:avoid; cursor:pointer; }
.airchecks input { margin-right:5px; }
details.bagpicker { padding:6px 16px; border-bottom:1px solid var(--line); background:#fff; }
details.bagpicker summary { font-size:13px; font-weight:bold; cursor:pointer; }
details.bagpicker .head { display:flex; gap:10px; align-items:center; margin:4px 0; }
details.bagpicker .head button { font-size:12px; padding:2px 8px; cursor:pointer; }
.bagchecks { column-width:220px; column-gap:16px; font-size:12px; max-height:180px; overflow-y:auto; overflow-x:hidden; border-top:1px solid var(--line); padding-top:4px; }
.bagchecks label { display:block; padding:1px 0; break-inside:avoid; cursor:pointer; }
.bagchecks input { margin-right:5px; }
.tablewrap { overflow-x:auto; padding:0 8px 40px; }
table { border-collapse:collapse; width:auto; min-width:100%; font-size:10px; }
th, td { border:1px solid var(--line); padding:3px 5px; text-align:center; white-space:nowrap; }
thead th { position:sticky; top:0; background:var(--head); z-index:2; font-size:9px; min-width:64px; }
thead th a { color:var(--fg); text-decoration:none; }
tbody th { text-align:left; font-weight:normal; font-size:10px; white-space:normal; min-width:150px; max-width:190px; background:#fff; position:sticky; left:0; z-index:1; }
td .cellbtn { font-size:10px; padding:1px 2px; }
td.ok { background:#dafbe1; color:var(--ok); font-weight:bold; }
td.warn { background:#fff8c5; color:var(--warn); font-weight:bold; }
td.no { background:#ffebe9; color:var(--no); font-weight:bold; }
td.unk { background:#f6f8fa; color:var(--unk); }
td.personal { outline:2px solid #0969da; outline-offset:-2px; }
button.cellbtn { border:0; background:inherit; cursor:pointer; font:inherit; width:100%; padding:2px 4px; }
.legend span { display:inline-block; margin-right:14px; font-size:12px; padding:2px 6px; border:1px solid var(--line); border-radius:4px; }
#detail { position:fixed; inset:auto 0 0 0; max-height:55vh; overflow:auto; background:#fff; border-top:2px solid var(--fg); padding:14px 20px; display:none; z-index:10; box-shadow:0 -4px 16px rgba(0,0,0,.15); }
#detail h3 { margin:0 0 8px; font-size:15px; }
#detail .close { float:right; font-size:13px; }
#detail table { min-width:0; }
.bagpage { max-width:900px; margin:0 auto; padding:0 16px 60px; }
.bagpage table { font-size:13px; }
a { color:#0969da; }
footer { border-top:1px solid var(--line); padding:14px 20px 30px; font-size:12px; color:var(--muted); }
@media (max-width:700px){ body{font-size:14px;} thead th{font-size:10px;} }
"""

JS = """
let DATA = null;
function $(s){ return document.querySelector(s); }
function esc(s){ return String(s).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }
fetch('data.js').then(r=>r.text()).then(t=>{ DATA = JSON.parse(t.replace(/^\\s*var MATRIX = /,'').replace(/;\\s*$/,'')); render(); });

const DEFAULT_AIRLINES = ['British Airways','Virgin Atlantic','easyJet','Ryanair','Jet2','Wizz Air','KLM','Lufthansa','Emirates','United'];
let selectedAirlines = null;
let selectedBags = null; // null = all

function loadSelection(){
  try {
    const s = JSON.parse(localStorage.getItem('bva_airlines') || 'null');
    if (Array.isArray(s) && s.length) return s;
  } catch(e) {}
  return DEFAULT_AIRLINES.filter(n => DATA.airlines.some(a => a.name === n));
}
function saveSelection(){
  localStorage.setItem('bva_airlines', JSON.stringify(selectedAirlines));
  localStorage.setItem('bva_bags', JSON.stringify(selectedBags));
}

function statusOf(cell){ return cell ? cell.status : 'unknown'; }

function render(){
  const bags = DATA.bags, airlines = DATA.airlines;
  selectedAirlines = loadSelection();
  try {
    const s = JSON.parse(localStorage.getItem('bva_bags') || 'null');
    selectedBags = Array.isArray(s) ? s : null;
  } catch(e) { selectedBags = null; }
  const bsel = $('#bagchecks');
  bsel.innerHTML = bags.map(b=>`<label title="${esc(b.name)}"><input type="checkbox" value="${esc(b.handle)}" ${!selectedBags || selectedBags.includes(b.handle)?'checked':''}>${esc(b.name)}</label>`).join('');
  bsel.querySelectorAll('input').forEach(cb=>cb.onchange=()=>{
    const c = [...bsel.querySelectorAll('input:checked')].map(i=>i.value);
    selectedBags = (c.length === bags.length) ? null : c;
    saveSelection(); drawTable();
  });
  $('#bagall').onclick = ()=>{ bsel.querySelectorAll('input').forEach(i=>i.checked=true); selectedBags = null; saveSelection(); drawTable(); };
  $('#bagnone').onclick = ()=>{ bsel.querySelectorAll('input').forEach(i=>i.checked=false); selectedBags = []; saveSelection(); drawTable(); };
  const box = $('#airchecks');
  box.innerHTML = airlines.map(a=>`<label><input type="checkbox" value="${esc(a.name)}" ${selectedAirlines.includes(a.name)?'checked':''}>${esc(a.name)}</label>`).join('');
  box.querySelectorAll('input').forEach(cb=>cb.onchange=()=>{
    selectedAirlines = [...box.querySelectorAll('input:checked')].map(i=>i.value);
    saveSelection(); drawTable();
  });
  $('#airall').onclick = ()=>{ box.querySelectorAll('input').forEach(i=>i.checked=true); selectedAirlines = DATA.airlines.map(a=>a.name); saveSelection(); drawTable(); };
  $('#airnone').onclick = ()=>{ box.querySelectorAll('input').forEach(i=>i.checked=false); selectedAirlines = []; saveSelection(); drawTable(); };
  drawTable();
}

function drawTable(){
  const airlines = DATA.airlines.filter(a=>selectedAirlines.includes(a.name));
  const rows = DATA.matrix.filter(r=>!selectedBags || selectedBags.includes(r.bag));
  let h = '<table><thead><tr><th>Bag</th>';
  for(const a of airlines) h += `<th><a href="${esc(a.source_url)}" target="_blank" rel="noopener">${esc(a.name)}</a><br><span style="font-weight:normal">${a.cabin_bag && a.cabin_bag.dims_cm ? esc(a.cabin_bag.dims_cm.join('x'))+'cm' : 'n/a'}</span></th>`;
  h += '</tr></thead><tbody>';
  for(const row of rows){
    const bag = DATA.bags.find(b=>b.handle===row.bag);
    h += `<tr><th><a href="bags/${esc(row.bag)}.html">${esc(row.bag_name)}</a> <a href="${esc(bag.url)}" target="_blank" rel="noopener" title="Briggs &amp; Riley product page" style="font-size:11px">[B&amp;R]</a><br><span style="color:#57606a">${esc(fmtDims(row))}</span></th>`;
    for(const a of airlines){
      const c = row.cells[a.name];
      const st = statusOf(c);
      const cls = c && c.fits_as_personal_item ? 'personal ' : '';
      h += `<td class="${cls}${st==='fits'?'ok':st==='fits_unexpanded_only'?'warn':st==='does_not_fit'?'no':'unk'}">`;
      h += `<button class="cellbtn" data-bag="${esc(row.bag)}" data-air="${esc(a.name)}">${st==='fits'?'FITS':st==='fits_unexpanded_only'?'UNEXP':'NO'}${c && c.fits_as_personal_item ? ' P' : ''}</button></td>`;
    }
    h += '</tr>';
  }
  h += '</tbody></table>';
  $('#matrix').innerHTML = h;
  document.querySelectorAll('.cellbtn').forEach(b=>b.onclick=()=>showDetail(b.dataset.bag, b.dataset.air));
}

function fmtDims(row){
  const b = DATA.bags.find(x=>x.handle===row.bag);
  let s = `${b.height_cm} x ${b.width_cm} x ${b.depth_cm} cm`;
  if(b.expanded_depth_cm) s += ` (exp. ${b.expanded_depth_cm})`;
  if(b.weight_kg) s += `, ${b.weight_kg} kg`;
  return s;
}

function showDetail(bagHandle, airName){
  const bag = DATA.bags.find(b=>b.handle===bagHandle);
  const al = DATA.airlines.find(a=>a.name===airName);
  const row = DATA.matrix.find(r=>r.bag===bagHandle);
  const cell = row.cells[airName];
  let h = `<button class="close" onclick="document.getElementById('detail').style.display='none'">Close</button>`;
  h += `<h3>${esc(bag.name)} &times; ${esc(al.name)}</h3>`;
  h += `<p class="meta">Bag: ${esc(fmtDims({bag:bagHandle}))} &mdash; <a href="${esc(bag.url)}" target="_blank" rel="noopener">Briggs &amp; Riley product page</a> (fetched ${esc((DATA.meta && DATA.meta.bags_fetched_at) || '')})</p>`;
  h += `<p class="meta">Airline cabin-bag limit: ${al.cabin_bag && al.cabin_bag.dims_cm ? esc(al.cabin_bag.dims_cm.join(' x ')) + ' cm' : 'not verified'}${al.cabin_bag && al.cabin_bag.weight_kg!=null ? ', max ' + al.cabin_bag.weight_kg + ' kg' : ''} &mdash; <a href="${esc(al.source_url)}" target="_blank" rel="noopener">${esc(al.name)} official page</a> (fetched ${esc(al.fetched_at || '')})</p>`;
  if(al.personal_item && al.personal_item.dims_cm) h += `<p class="meta">Personal item / underseat: ${esc(al.personal_item.dims_cm.join(' x '))} cm${al.personal_item.weight_kg!=null ? ', max '+al.personal_item.weight_kg+' kg':''}</p>`;
  if(al.notes) h += `<p class="meta">Notes: ${esc(al.notes)}</p>`;
  if(cell && cell.cabin_bag){
    const c = cell.cabin_bag;
    h += `<p><strong>Cabin bag:</strong> ${c.fits ? 'FITS' : "DOESN'T FIT"} &mdash; dimension margin ${c.dim_margin_cm} cm (smallest axis)${c.weight_limit_kg!=null ? `, weight remaining ${c.weight_remaining_kg} kg of ${c.weight_limit_kg} kg` : ''}.</p>`;
  }
  if(cell && cell.cabin_bag_expanded){
    const c = cell.cabin_bag_expanded;
    h += `<p><strong>Expanded (${bag.expanded_depth_cm} cm depth):</strong> ${c.fits ? 'FITS' : "DOESN'T FIT"} &mdash; margin ${c.dim_margin_cm} cm.</p>`;
  }
  if(cell && cell.personal_item){
    const c = cell.personal_item;
    h += `<p><strong>As personal item / underseat:</strong> ${c.fits ? 'FITS' : "DOESN'T FIT"} &mdash; margin ${c.dim_margin_cm} cm.</p>`;
  }
  h += `<p class="meta">Status: <strong>${esc(cell ? ({fits:'Fits',fits_unexpanded_only:'Fits unexpanded only',does_not_fit:"Doesn't fit",unknown:'Unknown'})[cell.status] : 'Unknown')}</strong></p>`;
  const d = $('#detail'); d.innerHTML = h; d.style.display = 'block';
}
"""


def esc(s):
    return html.escape(str(s), quote=True)


def page(title, body):
    return f"""<!doctype html>
<html lang="en-GB"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{esc(title)} - briggs-v-airlines</title>
<style>{CSS}</style></head><body>
<header><h1><a href="../index.html">briggs-v-airlines</a> <span class="meta" style="font-weight:normal">— which Briggs &amp; Riley cabin bags fit which airlines' cabin baggage limits</span></h1></header>
{body}
<footer>
<p><strong>Unofficial and independent.</strong> This site is not affiliated with, endorsed by, or connected to Briggs &amp; Riley or any airline. Bag dimensions and images are from briggs-riley.co.uk product pages; airline limits are from each airline's own official website, fetched on the date shown. Airlines change their rules without notice - always check the airline's own page before flying. No Briggs &amp; Riley logos or trademarks are used; product names are referenced nominatively only and product images are not reproduced (they link to Briggs &amp; Riley's own CDN).</p>
<p>Raw data as JSON: <a href="/bags.json">bags.json</a> · <a href="/airlines.json">airlines.json</a> · <a href="/matrix.json">matrix.json</a> · <a href="/meta.json">meta.json</a></p>
<p>Build script / source (re-run with <code>python run_all.py</code>): <a href="/src/run_all.py">run_all.py</a> · <a href="/src/README.md">README.md</a> · <a href="/src/scrapers/scrape_briggs.py">scrape_briggs.py</a> · <a href="/src/scrapers/scrape_airlines.py">scrape_airlines.py</a> · <a href="/src/scrapers/build_airlines.py">build_airlines.py</a> · <a href="/src/scrapers/build_matrix.py">build_matrix.py</a> · <a href="/src/scrapers/build_site.py">build_site.py</a></p>
</footer></body></html>"""


def index_body(data):
    fetched = data["meta"]["fetched_at"]
    nbags = len(data["bags"])
    nair = len(data["airlines"])
    unver = [a["name"] for a in data["airlines"] if not a.get("verified", True)]
    return f"""
<p class="disclaimer">Independent, unofficial comparison - not affiliated with Briggs &amp; Riley or any airline. Data scraped from briggs-riley.co.uk and each airline's own official page, fetched <strong>{esc(fetched)}</strong>. {nbags} bags &times; {nair} airlines. Re-run: <code>python run_all.py</code>.</p>
<details class="bagpicker">
  <summary>Bags shown (multi-select)</summary>
  <div class="head"><button id="bagall" type="button">All</button><button id="bagnone" type="button">None</button><span class="meta">saved on this device</span></div>
  <div class="bagchecks" id="bagchecks"></div>
</details>
<div class="airpicker">
  <div class="head"><strong>Airlines shown (pick your favourites):</strong>
    <button id="airall" type="button">All</button>
    <button id="airnone" type="button">None</button>
    <span class="meta">saved on this device</span>
  </div>
  <div class="airchecks" id="airchecks"></div>
</div>
<p class="meta" style="padding:6px 20px">Legend:
<span class="legend"><span style="background:#dafbe1;color:#1a7f37;font-weight:bold">FITS</span>
<span style="background:#fff8c5;color:#9a6700;font-weight:bold">UNEXP</span> fits unexpanded only (expanded depth exceeds the limit)
<span style="background:#ffebe9;color:#cf222e;font-weight:bold">NO</span> doesn't fit (1 cm over is still "no" - click the cell for the margin)
<span style="background:#f6f8fa;color:#6e7781">?</span> unknown
<span style="outline:2px solid #0969da">P</span> also fits as the personal/underseat item. Click any cell for the numbers and source links.</span></p>
<div class="tablewrap"><div id="matrix"></div></div>
<div id="detail"></div>
<script>{JS}</script>
"""


def bag_page(data, bag, matrix_row):
    al = data["airlines"]
    cells = matrix_row["cells"]
    rows = []
    for a in al:
        c = cells.get(a["name"], {})
        st = c.get("status", "unknown")
        cb = c.get("cabin_bag") or {}
        pe = c.get("personal_item") or {}
        cab = a.get("cabin_bag") or {}
        per = a.get("personal_item") or {}
        rows.append(
            f"<tr><td><a href='{esc(a['source_url'])}' target='_blank' rel='noopener'>{esc(a['name'])}</a></td>"
            f"<td>{esc(cab.get('dims_cm') and ' x '.join(map(str, cab['dims_cm'])) + ' cm') or 'n/a'}"
            f"{(' / ' + str(cab['weight_kg']) + ' kg') if cab.get('weight_kg') is not None else ''}</td>"
            f"<td>{esc(per.get('dims_cm') and ' x '.join(map(str, per['dims_cm'])) + ' cm') or 'n/a'}</td>"
            f"<td class='{STATUS_CLASS[st]}'>{esc(STATUS_LABEL[st])}</td>"
            f"<td>{esc(cb.get('dim_margin_cm') if cb else '')}</td>"
            f"<td>{esc(cb.get('weight_remaining_kg') if cb else '')}</td>"
            f"<td>{'yes' if c.get('fits_as_personal_item') else ('no' if pe else '')}</td></tr>")
    dims = f"{bag['height_cm']} x {bag['width_cm']} x {bag['depth_cm']} cm"
    if bag.get("expanded_depth_cm"):
        dims += f" (expanded depth {bag['expanded_depth_cm']} cm)"
    weight = f"{bag['weight_kg']} kg" if bag.get("weight_kg") else "n/a"
    return f"""
<div class="bagpage">
<p class="meta"><a href="../index.html">&larr; full matrix</a></p>
<h1>{esc(bag['name'])}</h1>
<p class="meta">Exterior dimensions (incl. wheels &amp; handles): <strong>{esc(dims)}</strong> &middot; weight {esc(weight)}
{f" &middot; capacity {bag['capacity_litres'][0]} - {bag['capacity_litres'][1]} L" if bag.get('capacity_litres') else ''}<br>
<a href="{esc(bag['url'])}" target="_blank" rel="noopener">Briggs &amp; Riley product page</a> &middot; SKU {esc(bag.get('sku') or 'n/a')} &middot; fetched {esc(data['meta']['bags_fetched_at'])}</p>
<table><thead><tr><th>Airline</th><th>Cabin bag limit</th><th>Personal item</th><th>Result</th><th>Dim margin (cm)</th><th>Weight remaining (kg)</th><th>Fits as personal item</th></tr></thead>
<tbody>{''.join(rows)}</tbody></table>
<p class="meta">Fit rule: each bag dimension (sorted largest first) must be &le; the airline's limit dimension sorted the same way; 1 cm over = doesn't fit. Weight: bag empty weight must be &le; the airline's cabin bag weight limit.</p>
</div>
"""


def main():
    data = json.loads((DATA / "matrix.json").read_text(encoding="utf-8"))
    meta = json.loads((DATA / "meta.json").read_text(encoding="utf-8"))
    payload = dict(data)
    payload["meta"] = meta
    # expose raw JSON alongside the site
    import shutil
    for f in ("bags.json", "airlines.json", "matrix.json", "meta.json"):
        shutil.copy(DATA / f, SITE / f)
    # publish the whole build script / source so the pipeline is reproducible
    srcdir = SITE / "src"
    srcdir.mkdir(exist_ok=True)
    shutil.copy(ROOT / "run_all.py", srcdir / "run_all.py")
    shutil.copy(ROOT / "README.md", srcdir / "README.md")
    scdir = srcdir / "scrapers"
    scdir.mkdir(exist_ok=True)
    for f in (ROOT / "scrapers").glob("*.py"):
        shutil.copy(f, scdir / f.name)
    (SITE / "data.js").write_text(
        "var MATRIX = " + json.dumps(payload, ensure_ascii=False) + ";\n", encoding="utf-8")
    (SITE / "index.html").write_text(page("Fit matrix", index_body(payload)), encoding="utf-8")
    bagsdir = SITE / "bags"
    bagsdir.mkdir(exist_ok=True)
    for row in data["matrix"]:
        bag = next(b for b in data["bags"] if b["handle"] == row["bag"])
        (bagsdir / f"{row['bag']}.html").write_text(
            page(row["bag_name"], bag_page(payload, bag, row)), encoding="utf-8")
    print(f"site built: index + {len(data['matrix'])} bag pages -> {SITE}")


if __name__ == "__main__":
    main()
