#!/usr/bin/env python3
"""BPF26 Agenda Block v8 — build din Airtable (instantaneu 06.10.2026, ~09:52).
Aceeasi logica de transformare ca bpf-agenda-proxy.php v1.2, ca instantaneul
si datele live sa arate identic."""
import json, re, sys, importlib.util
from datetime import datetime, timedelta, timezone

spec = importlib.util.spec_from_file_location("src", "airtable_2026-10-06c.py")
src = importlib.util.module_from_spec(spec); spec.loader.exec_module(src)

STAMP = "06.10.2026"
BUILD = "2026-10-06"
VERSION = "v8"
TZ = timezone(timedelta(hours=3))          # EEST; festivalul e integral inainte de 25.10

TYPE_LABEL = {'Exhibition':'Exhibition','Installation':'Installation','Film Screening':'Film',
  'Workshop':'Workshop','Masterclass':'Masterclass','Guided Tour':'Guided tour',
  'Photo Book':'Photobook','Photo Walk':'Photo walk','Live Music':'Live',
  'Networking Event':'Night event','Lecture':'Lecture','Panel Discussion':'Talk','Portfolio Review':'Portfolio review'}
VENUE_SHORT = {'CdRF - Centrul de Resurse în Fotografie':'CdRF',
               'National Museum of Maps and Old Books':'Museum of Maps and Old Books'}
HIDE_PEOPLE = {'collective','to be announced','tba'}
# Raman in Airtable, dar NU apar pe site (decizie 06.10.2026: sold out, ca sa nu creeze confuzie).
# Aceeasi lista e in bpf-agenda-proxy.php (BPF_HIDE_IDS) si, din v7, si in JS-ul blocului (HIDE). Se intoarce stergand ID-ul din ambele.
HIDE_IDS = {
  'recrHpqAramtRO7yE',  # In Plain Sight I  - workshop x Save the Children, sam 10.10
  'recMi0WvV6BHku1h6',  # In Plain Sight II - workshop x Save the Children, sam 10.10
  'rec852oA3g6ZRlsSK',  # Somewhere to Look From - workshop x UNHCR, dum 11.10
}

def title(t):
    t = t.strip()
    t = re.sub(r'\s+-\s+', ' — ', t)
    t = re.sub(r'\bw/(?=\S)', 'w/ ', t)
    return t
def addr(a):
    a = re.sub(r',?\s*(\d{6}\s*)?Bucure[sș]ti.*$', '', a.strip(), flags=re.I)
    return a.strip(' ,')
def dur(m):
    return f"{m//60}h" if m % 60 == 0 else f"{m//60}h{m%60:02d}"

ev, ov = [], []
for (rid, t, ty, s, e, v, people, co) in src.R:
    if rid in HIDE_IDS: continue
    ppl = [p for p in people if p and p.strip().lower() not in HIDE_PEOPLE]
    a = f"{ppl[0]} +{len(ppl)-1}" if len(ppl) > 3 else ", ".join(ppl)
    co = [('International' if c.strip().lower() == 'international' else c.strip()) for c in co if c.strip()]
    c = "International" if not co else " · ".join(co)
    base = dict(id=rid, t=title(t), ty=ty, tyl=TYPE_LABEL.get(ty, ty),
                v=VENUE_SHORT.get(v, v), ad=addr(src.VEN.get(v, '')), a=a, c=c)
    if not s:
        ov.append(base); continue
    S = datetime.fromisoformat(s.replace('Z', '+00:00')).astimezone(TZ)
    E = datetime.fromisoformat(e.replace('Z', '+00:00')).astimezone(TZ) if e else None
    mins = int((E - S).total_seconds() // 60) if (E and E > S) else 0
    d = S.strftime('%Y-%m-%d')
    ev.append({**base, 'd': d, 's': S.strftime('%H:%M'),
               'e': E.strftime('%H:%M') if (E and E > S) else '',
               'dur': dur(mins) if mins else '',
               'hero': d in ('2026-10-09', '2026-10-18')})

ev.sort(key=lambda x: (x['d'], x['s'], x['v'], x['t']))
ov.sort(key=lambda x: (x['v'], x['t']))
types = sorted(set([x['tyl'] for x in ev] + [x['tyl'] for x in ov]))
venues = sorted(set([x['v'] for x in ev] + [x['v'] for x in ov]) - {''})

WD = ['MON','TUE','WED','THU','FRI','SAT','SUN']
FULL = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
days = []
for n in range(9, 19):
    dt = datetime(2026, 10, n)
    days.append(dict(iso=dt.strftime('%Y-%m-%d'), n=n, wd=WD[dt.weekday()],
                     full=FULL[dt.weekday()], hero=n in (9, 18)))

D = dict(ev=ev, ov=ov, days=days, types=types, venues=venues, stamp=STAMP)
json.dump(D, open('data_v8.json', 'w'), ensure_ascii=False, indent=1)

tpl = open('template_v8.html', encoding='utf-8').read()
out = (tpl.replace('@@VERSION@@', VERSION).replace('@@BUILD@@', BUILD)
          .replace('@@STAMP@@', STAMP)
          .replace('@@HIDE@@', json.dumps(sorted(HIDE_IDS)))
          .replace('@@DATA@@', json.dumps(D, ensure_ascii=False)))
open('bpf-agenda-block.html', 'w', encoding='utf-8').write(out)
print(f"ev={len(ev)} ov={len(ov)} types={len(types)} venues={len(venues)} bytes={len(out.encode())}")
