"""Costruisce en.html (versione inglese per The Pudding Cup) a partire da index.html.
Sostituisce testo della lettera, legende, scritte dentro i grafici, titoli di coda e cartolina.
Ogni sostituzione è controllata: se una stringa non si trova, lo script si ferma."""
import pathlib, re, sys
H = pathlib.Path(__file__).parent
s = (H/'index.html').read_text()
CH_EN = pathlib.Path(sys.argv[1]).read_text()

def rep(a, b, count=1):
    global s
    n = s.count(a)
    if n < count: raise SystemExit(f'non trovato ({n}): {a[:90]}')
    s = s.replace(a, b) if count == 0 else s.replace(a, b, count)

def rep_all(a, b):
    global s
    if a not in s: raise SystemExit(f'non trovato: {a[:90]}')
    s = s.replace(a, b)

# --- testo della lettera (tutti i capitoli)
i = s.index('const CH=['); j = s.index('];', s.index(' {id:"azzurro",', i)) + 2
s = s[:i] + CH_EN.strip() + s[j:]

# --- pagina
rep('<html lang="it">', '<html lang="en">')
rep('<title>Cara Chiara</title>', '<title>Dear Chiara</title>')
rep('content="Una lettera d’amore scritta con i dati. A volte, la statistica sbaglia."', 'content="A love letter written in data. Sometimes, statistics get it wrong."')
rep('<div id="hint" class="ui">scorri ↓</div>', '<div id="hint" class="ui">scroll ↓</div>')
rep('Cara Chiara: una lettera d’amore scritta con i dati</h1>', 'Dear Chiara: a love letter written in data</h1>')
i = s.index('<section class="after" id="after">'); j = s.index('</section>', i) + len('</section>')
s = s[:i] + '''<section class="after" id="after"><div class="wrap">
  <p class="sig">— for <em>Chiara</em></p>
  <button id="cartolina">Save the postcard ↓</button>
  <h2>Sources</h2>
  <p><b>Tickling.</b> S.-J. Blakemore, D. Wolpert, C. Frith, “Central cancellation of self-produced tickle sensation”, <i>Nature Neuroscience</i> 1, 1998.</p>
  <p><b>Heartbeats.</b> J. Helm, D. Sbarra, E. Ferrer, “Assessing cross-partner associations in physiological responses via coupled oscillator models”, <i>Emotion</i>, 2012: 32 couples.</p>
  <p><b>Kissing to the right.</b> O. Güntürkün, “Adult persistence of head-turning asymmetry”, <i>Nature</i> 421, 2003: 124 couples observed in the US, Germany and Turkey, 80 turning right (64.5%).</p>
  <p><b>The kiss is not universal.</b> W. Jankowiak, S. Volsche, J. Garcia, “Is the romantic–sexual kiss a near human universal?”, <i>American Anthropologist</i> 117, 2015: present in 46% of 168 cultures (77), no evidence in the other 91. Based on ethnographic records.</p>
  <p><b>“I love you”.</b> J. Ackerman, V. Griskevicius, N. Li, “Let’s get serious: communicating commitment in romantic relationships”, <i>Journal of Personality and Social Psychology</i> 100, 2011. Study 1: people believe women say it after 54.7 days and men after 77.8. Study 2: men recall starting to think about it after 97.3 days, women after 138.9 (two different measures: one is an expectation, the other a memory). Study 3: in 70% of couples (28 of 40) he said it first.</p>
  <p><b>Meeting online.</b> M. Rosenfeld, R. Thomas, S. Hausen, “Disintermediating your friends”, <i>PNAS</i> 116, 2019: 39% of heterosexual couples who met in the US in 2017 met online.</p>
  <p><b>Marriages in Italy.</b> ISTAT (Italian National Institute of Statistics), marriage survey 2023, tables 2.5 and 2.15. Couples with both spouses born in Italy: 146,120; same region 76.2% (8.6% by chance). Groom born in Tuscany and bride born in Piedmont: 90; the other way round, 78. Groom born in Tuscany and bride born abroad: 1,094 of 8,639 Tuscan grooms (12.7%); across Italy 18,684 of 164,804 (11.3%).</p>
  <p><b>Region by region.</b> Share of grooms born in a region who marry a woman born in the same region, 2004 and 2023 (ISTAT, table 2.15). It falls in 17 of 20 regions. Nationally, couples from different regions went from 20.1% (2004) to 23.6% (2013) and 23.8% (2023). Aosta Valley and Molise have only a few hundred weddings, so their changes are less certain. Over twenty years, marriages between people born in Italy fell from 207,136 to 146,120 and spouses got older: the comparison describes who gets married, not the whole population.</p>
  <p><b>Education.</b> ISTAT 2023, table 2.5: ratio between observed couples with the same level of education and those expected by chance. Postgraduate 17.2× (265 couples), primary 9.3× (1,214), degree 2.2× (16,121), short degree 2.0×, lower secondary 1.9×, high school 1.2× (41,953).</p>
  <p><b>New words.</b> A. Aron, M. Paris, E. Aron, “Falling in love: Prospective studies of self-concept change”, <i>Journal of Personality and Social Psychology</i> 69, 1995: 329 students, five measurements over ten weeks.</p>
  <p><b>The house.</b> Everything in the drawing comes from our messages; “in both” means we both wrote it.</p>
  <h2>Method</h2>
  <p>“By chance” is the share of matching couples you would get by pairing brides and grooms at random, keeping how many people are in each group. In the thread diagram each thread is 100 couples (rounded with the largest-remainder method: 1,648 threads for 164,804 couples); regions run north to south and the width of each bar is proportional to its grooms or brides; brides born abroad are the last bar, in blue. The drive is the route as remembered, rebuilt on OpenStreetMap streets; it ends at the start of via Genova, with no house number. Streets © OpenStreetMap contributors. Visual identity: trame kit 1.5.</p>
</div></section>''' + s[j:]

# --- numeri in formato inglese
rep('const it=x=>Math.round(x).toLocaleString("it-IT");', 'const it=x=>Math.round(x).toLocaleString("en-US");')
rep_all('.replace(".",",")', '')

# --- titolo e finale
rep('ctx.fillText("Cara",M?20:W*.08,H*.46)', 'ctx.fillText("Dear",M?20:W*.08,H*.46)')
rep('ctx.fillText("una lettera d’amore scritta con i dati.",', 'ctx.fillText("a love letter written in data.",')
rep('ctx.fillText("Per Chiara.",', 'ctx.fillText("For Chiara.",')

# --- I · solletico: la parola chiave è di due parole («tickle me»), con lo spazio
rep('P.adesso=(s,L,K,m,t,k)=>{const word=K.slice(0,-1).map(i=>L.chars[i]),big=M?W*.19:Math.min(W*.155,250);ctx.font=F(700,big);\n  const ws=word.map(o=>ctx.measureText(o.ch).width-big*.045);let tx=(W-ws.reduce((a,b)=>a+b,0))/2;',
    'P.adesso=(s,L,K,m,t,k)=>{const word=K.map(i=>L.chars[i]).filter(o=>!/[.,!?]/.test(o.ch)),big=M?W*.17:Math.min(W*.14,230);ctx.font=F(700,big);\n  const ws=word.map((o,j)=>ctx.measureText(o.ch).width-big*.045+(j<word.length-1&&word[j+1].word!==o.word?big*.26:0));let tx=(W-ws.reduce((a,b)=>a+b,0))/2;')
rep('word.forEach((o,j)=>{const gx=tx+ws[j]/2,gy=H*(M?.55:.5);tx+=ws[j];', 'word.forEach((o,j)=>{const cw0=ctx.measureText(o.ch).width-big*.045,gx=tx+cw0/2,gy=H*(M?.55:.5);tx+=ws[j];')
rep('const ring="mi rincorri per casa · ti scappo · mi rincorri per casa · ti scappo · "', 'const ring="you chase me · I run away · you chase me · I run away · "')

# --- II · giorni: «Sky blue» a sinistra (con lo spazio), griglia di «s»
rep('P.giorni=(s,L,K,m,t)=>{const kw=K.slice(0,-1).map(i=>L.chars[i]);', 'P.giorni=(s,L,K,m,t)=>{const kw=K.map(i=>L.chars[i]).filter(o=>!/[.,!?]/.test(o.ch));')
rep('mixc(C.ink,C.electric,m));hx+=cw-hs*.03});', 'mixc(C.ink,C.electric,m));hx+=cw-hs*.03;const nx=kw[kw.indexOf(o)+1];if(nx&&nx.word!==o.word)hx+=hs*.24});')
rep_all('glyph("a",lerp(src.x+src.w/2,lx,tt)', 'glyph("s",lerp(src.x+src.w/2,lx,tt)')

# --- III · casa: etichette
for a, b in [('"una cascina"', '"a farmhouse"'), ('"le finestre grandi"', '"big windows"'), ('"la luce calda della sera"', '"warm evening light"'),
             ('"candele, esorbitanti"', '"candles, unreasonably many"'), ('"la Val d’Orcia, i cipressi"', '"Val d’Orcia, cypresses"'), ('"il divano"', '"the sofa"'),
             ('"la cucina a isola"', '"kitchen island"'), ('"l’orto"', '"vegetable patch"'), ('"le pareti pastello"', '"pastel walls"'), ('"la vasca"', '"the bathtub"'),
             ('"niente porte"', '"no doors"'), ('"due piani, in mattone"', '"two storeys, brick"'), ('"le piante"', '"plants"'),
             ('"lo spazio aperto per gli amici"', '"open space for friends"'), ('"le arcate vetrate"', '"glass arches"'), ('"il cagnolone, i cavalli"', '"a big dog, horses"')]:
    rep(a, b)
rep('"6 cose in comune, in giallo":"cosa c’è nella casa"', '"6 things in common, in yellow":"what’s in the house"')

# --- IV · cuore
rep('[[K[0]||[],M?W*.27:W*.32,b1,"io"],[K[1]||[],M?W*.73:W*.68,b2,"tu"]]', '[[K[0]||[],M?W*.25:W*.3,b1,"me"],[K[1]||[],M?W*.72:W*.68,b2,"you"]]')
rep('P.cuore=(s,L,K,m,t,k,kp)=>{const sync=k<0?0:ease((k+kp)/1.3);const big=M?W*.3:Math.min(W*.26,420);', 'P.cuore=(s,L,K,m,t,k,kp)=>{const sync=k<0?0:ease((k+kp)/1.3);const big=M?W*.19:Math.min(W*.15,H*.3,250);')
rep('sync>.97?"in sincronia":"fuori fase"', 'sync>.97?"in sync":"out of sync"')

# --- V · baci
rep_all('glyph("bacio",', 'glyph("kiss",')
rep('const big=M?Math.min(W*.12,48):Math.min(W*.07,H*.11,110);', 'const big=M?Math.min(W*.085,34):Math.min(W*.05,H*.08,80);')
rep_all('"ti amo"', '"I love you"')
rep('ctx.fillText("QUANDO SI CREDE CHE LO DICANO"', 'ctx.fillText("WHEN PEOPLE THINK THEY SAY IT"')
rep('ctx.fillText("QUANDO DICONO DI AVERCI PENSATO"', 'ctx.fillText("WHEN THEY SAY THEY FIRST THOUGHT ABOUT IT"')
rep('ctx.fillText("CHI L’HA DETTO PRIMA, OGNI 10 COPPIE"', 'ctx.fillText("WHO SAID IT FIRST, IN EVERY 10 COUPLES"')
rep('[["lui",77.8,97.3,C.electric,700,false,-1],["lei",54.7,138.9,C.flame,400,true,1]]', '[["him",77.8,97.3,C.electric,700,false,-1],["her",54.7,138.9,C.flame,400,true,1]]')
rep('`${who} · ${d.toFixed(1)} giorni`', '`${who} · ${d.toFixed(1)} days`')
rep('d===150?"150 giorni":String(d)', 'd===150?"150 days":String(d)')
rep('M?12:Math.min(22,W*.016),i<7?700:400,i>=7', 'M?9:Math.min(15,W*.011),i<7?700:400,i>=7')

# --- VI · incontro
rep_all('glyph("coppia",', 'glyph("couple",')

# --- VII · strada
rep('["lungo Po",.31]', '["Po riverside",.31]')

# --- VIII · Italia: nomi delle regioni in inglese, scritte del diagramma
rep('let SK={};', '''let SK={};const RN_EN={"Piemonte":"Piedmont","Valle d'Aosta":"Aosta Valley","Lombardia":"Lombardy","Trentino-Alto Adige":"Trentino-S. Tyrol","Friuli-Venezia Giulia":"Friuli-V. Giulia","Toscana":"Tuscany","Puglia":"Apulia","Sicilia":"Sicily","Sardegna":"Sardinia","estero":"abroad"},RN=n=>RN_EN[n]||n;
const ST_EN={"Elementare":"primary","Media":"lower secondary","Diploma":"high school","Diploma univ.":"short degree","Laurea":"degree","Post-laurea":"postgraduate"};''')
rep('const name=SHORT[nm]||nm;', 'const name=RN(nm);')
rep('ctx.fillText(SHORT[nm]||nm,xL-(M?8:14),y);', 'ctx.fillText(RN(nm),xL-(M?8:14),y);')
rep('[["sposo",yT],["sposa",yB]]', '[["groom",yT],["bride",yB]]')
rep_all('w2==="sposo"', 'w2==="groom"')
rep('lines.push(`${nm} · ${it(tot)} sposi`,`${(100*same/tot).toFixed(1)}% sposa una donna nata in ${nm}`,`${(100*est2/tot).toFixed(1)}% una donna nata all’estero`)',
    'lines.push(`${RN(nm)} · ${it(tot)} grooms`,`${(100*same/tot).toFixed(1)}% marry a woman born in ${RN(nm)}`,`${(100*est2/tot).toFixed(1)}% a woman born abroad`)')
rep('lines.push(`estero · ${it(SK.Cc[i])} spose`,"nate all’estero, con uno sposo nato in Italia")', 'lines.push(`abroad · ${it(SK.Cc[i])} brides`,"born abroad, married to a groom born in Italy")')
rep('lines.push(`${nm} · ${it(tot)} spose`,`${(100*same/tot).toFixed(1)}% sposa un uomo nato in ${nm}`)', 'lines.push(`${RN(nm)} · ${it(tot)} brides`,`${(100*same/tot).toFixed(1)}% marry a man born in ${RN(nm)}`)')
rep('M?"tocca una regione":"passa sopra una regione"', 'M?"tap a region":"hover over a region"')
rep('"· quota di sposi che sposa una donna nata nella propria regione"', '"· share of grooms marrying a woman born in their own region"')
rep('`${o.t.toLowerCase()} · ${it(o.coppie)} coppie`', '`${ST_EN[o.t]||o.t} · ${it(o.coppie)} couples`')
rep('hl=nm==="Toscana",pr=', 'hl=nm==="Toscana",pr=')

# --- IX · noi: «And yet.» con lo spazio, righe e fascia in inglese
rep('const row="stessa provincia · stessi studi · stesso mestiere · stessa provincia · stessi studi · stesso mestiere · ";', 'const row="same province · same degree · same job · same province · same degree · same job · ";')
rep('ctx.fillText("noi",x,2);x+=bh*1.7', 'ctx.fillText("us",x,2);x+=bh*1.4')
rep('const tw=word.reduce((a,o)=>a+ctx.measureText(o.ch).width-big*.04+(o.ch==="E"?big*.22:0),0);', 'const gapAt=j=>j<word.length-1&&word[j+1].word!==word[j].word?big*.22:0;const tw=word.reduce((a,o,j)=>a+ctx.measureText(o.ch).width-big*.04+gapAt(j),0);')
rep('word.forEach(o=>{const w=ctx.measureText(o.ch).width;glyph(o.ch,lerp(o.x+o.w/2,tx+w/2,m),lerp(o.y,M?H*.6:H*.22,m),lerp(L.size,big,m),400,m>.5,C.ink);tx+=w-big*.04+(o.ch==="E"?big*.22:0)});',
    'word.forEach((o,j)=>{const w=ctx.measureText(o.ch).width;glyph(o.ch,lerp(o.x+o.w/2,tx+w/2,m),lerp(o.y,M?H*.6:H*.22,m),lerp(L.size,big,m),400,m>.5,C.ink);tx+=w-big*.04+gapAt(j)});')

# --- X · dopo e finale
rep('txt="fra dieci anni · nessuno lo sa · i dati meno di tutti · "', 'txt="in ten years · nobody knows · the data least of all · "')
rep('glyph("azzurro",x,y,ch*.8,', 'glyph("sky blue",x,y,ch*.8,')
rep('const rows=M?22:18,cw=M?110:190,ch=H/rows;sd=5;', 'const rows=M?22:18,cw=M?150:240,ch=H/rows;sd=5;')

# --- cartolina: testi bilingui dentro lo script


# --- blocco autore
rep('<p class="k">Chi l’ha fatta</p>', '<p class="k">Made by</p>')
rep('<p>Se le chiedessero che lavoro faccio, credo che Chiara direbbe: «Si mette al computer e fa succedere delle cose». Di solito le cose sono comunicazione strategica, sondaggi, visual e data journalism. Questa volta è successa una lettera.</p>', '<p>If you asked Chiara what I do, I think she’d say: “He sits at the computer and makes things happen.” Usually the things are strategic communication, polling, and visual and data journalism. This time, what happened was a letter. <a href="process.html" style="color:var(--lemon)">How I made it →</a></p>')
rep('<span>progetti e data journalism</span>', '<span>projects and data journalism</span>')
rep('<span>per contatti e lavoro</span>', '<span>get in touch</span>')
rep('<span>divulgazione storica e dataviz</span>', '<span>history storytelling and dataviz</span>')

rep('<p class="k">Lo studio</p>', '<p class="k">The studio</p>')
rep('<p class="say">trame è il mio studio di giornalismo visuale. Il nome viene dai fili di un tessuto e dagli intrecci di un racconto: prendo dati verificati e li intreccio in storie che si possono guardare, toccare e capire.</p>', '<p class="say">trame is my visual journalism studio. In Italian, <i>trame</i> are both the threads of a fabric and the plots of a story: I take verified data and weave it into stories you can look at, touch and understand.</p>')
rep('<p>Vuole essere un posto dove i numeri non servono a impressionare, ma a far vedere le persone che ci sono dietro. Ogni numero ha una fonte, ogni storia un metodo dichiarato.</p>', '<p>It wants to be a place where numbers are not there to impress, but to show the people behind them. Every figure has a source; every story, a stated method.</p>')

(H/'en.html').write_text(s)
left = sorted(set(re.findall(r'"[^"<>]*(?:\bche\b|\bdella\b|\bdegli\b|\bnella\b|\bsposi\b|\bgiorni\b|\bcoppie\b|\bstessa\b)[^"<>]*"', s)))
print('en.html scritto.', 'Stringhe italiane rimaste:' if left else 'Nessuna stringa italiana rimasta.', left[:20])
