#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
wa_diario.py — trasforma le chat esportate da WhatsApp in diari (pagine HTML, stampabili in PDF).
Usa solo la libreria standard di Python 3.8+: non serve installare nulla. Tutto resta sul tuo computer.

Ogni chat esportata (file .zip, oppure file .txt con le foto accanto) diventa un diario a sé,
con i messaggi giorno per giorno, foto, video, vocali e documenti. Viene creato anche un indice
di tutte le chat.

Uso:   python3 wa_diario.py  "WhatsApp Chat - Mamma.zip"  [altre chat ...]  --io "Il tuo nome"
       python3 wa_diario.py  *.zip  --io "Il tuo nome"
Aiuto: python3 wa_diario.py --help
"""
import argparse
import datetime as dt
import glob
import html
import re
import shutil
import sys
import tempfile
import zipfile
from pathlib import Path

MESI = ["", "gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio",
        "agosto", "settembre", "ottobre", "novembre", "dicembre"]
GIORNI = ["lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato", "domenica"]
MONTHS = ["", "January", "February", "March", "April", "May", "June", "July",
          "August", "September", "October", "November", "December"]
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
LINGUA = "it"

IMG_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic", ".bmp"}
VIDEO_EXT = {".mp4", ".mov", ".m4v", ".3gp", ".webm", ".mkv"}
AUDIO_EXT = {".opus", ".m4a", ".mp3", ".aac", ".ogg", ".wav", ".amr"}

TESTI = {
    "it": {"messaggi": "messaggi", "media": "foto, video e vocali", "dal": "dal", "al": "al",
           "partecipanti": "Partecipanti", "omesso": "contenuto non incluso nell'esportazione",
           "creato": "Diario creato il", "indice": "Le mie chat WhatsApp", "chat": "chat",
           "sotto": "Una conversazione WhatsApp", "allegato": "allegato", "vocale": "messaggio vocale",
           "nessuno": "nessun messaggio trovato"},
    "en": {"messaggi": "messages", "media": "photos, videos and voice notes", "dal": "from", "al": "to",
           "partecipanti": "Participants", "omesso": "content not included in the export",
           "creato": "Diary created on", "indice": "My WhatsApp chats", "chat": "chats",
           "sotto": "A WhatsApp conversation", "allegato": "attachment", "vocale": "voice message",
           "nessuno": "no messages found"},
}


def T(k):
    return TESTI[LINGUA][k]


def data_breve(d):
    return f"{MONTHS[d.month]} {d.day}, {d.year}" if LINGUA == "en" else f"{d.day} {MESI[d.month]} {d.year}"


def data_lunga(d):
    if LINGUA == "en":
        return f"{DAYS[d.weekday()]}, {MONTHS[d.month]} {d.day}, {d.year}"
    return f"{GIORNI[d.weekday()].capitalize()} {d.day} {MESI[d.month]} {d.year}"


def nome_mese(n):
    return MONTHS[n] if LINGUA == "en" else MESI[n]


# ---------------------------------------------------------------- lettura

INVISIBILI = dict.fromkeys(map(ord, "‎‏‪‫‬‭‮﻿"), None)
ORA = r"(\d{1,2})[:.](\d{2})(?:[:.](\d{2}))?\s*([AaPp]\.?\s?[Mm]\.?)?"
DATA = r"(\d{1,4})[./-](\d{1,2})[./-](\d{1,4}),?\s+"
RX_IOS = re.compile(r"^\[" + DATA + ORA + r"\]\s?(.*)$")          # [27/11/26, 09:35:12] Nome: testo
RX_AND = re.compile(r"^" + DATA + ORA + r"\s[-–]\s(.*)$")          # 27/11/26, 09:35 - Nome: testo
RX_MITTENTE = re.compile(r"^([^:\n]{1,80}?): (.*)$", re.S)
RX_ALLEG_IOS = re.compile(r"<[^<>]{2,40}?:\s*([^<>]+?)>")         # <allegato: 0001-PHOTO-….jpg>
RX_ALLEG_AND = re.compile(r"(\S+\.\w{2,5}) \([^()\n]{4,40}\)")     # IMG-2020…jpg (file allegato)
RX_NOMEFILE = re.compile(r"[\w.-]+\.\w{2,5}")
RX_OMESSO = re.compile(r"^<?\s*[\w ]{0,40}?(omess[oaie]|omitted|omitido|omitida|omis|weggelassen|ausgeschlossen)\s*>?$", re.I)


def pulisci(riga):
    return riga.translate(INVISIBILI).replace(" ", " ").replace("\xa0", " ").rstrip("\r\n")


def leggi_righe(txt):
    grezzi = []
    with open(txt, encoding="utf-8", errors="replace") as f:
        for riga in f:
            sistema = bool(re.search(r": \u200e(?!<)", riga))  # iOS: avvisi di sistema dopo "Nome: "
            riga = pulisci(riga)
            m = RX_IOS.match(riga) or RX_AND.match(riga)
            if m:
                a, b, c, h, mi, s, ampm, resto = m.groups()
                grezzi.append({"n": (int(a), int(b), int(c)), "lena": len(a), "h": int(h), "mi": int(mi),
                               "s": int(s or 0), "ampm": ampm, "resto": resto, "sistema": sistema})
            elif grezzi:
                grezzi[-1]["resto"] += "\n" + riga
    return grezzi


def costruisci_date(grezzi, mese_prima):
    normali = [g["n"] for g in grezzi if g["lena"] < 4]
    if mese_prima is None:
        if any(a > 12 for a, b, c in normali):
            mese_prima = False
        elif any(b > 12 for a, b, c in normali):
            mese_prima = True
        else:
            mese_prima = False
    for g in grezzi:
        a, b, c = g["n"]
        if g["lena"] == 4:
            y, mo, d = a, b, c
        else:
            y = c + 2000 if c < 100 else c
            mo, d = (a, b) if mese_prima else (b, a)
        h = g["h"]
        if g["ampm"]:
            pm = g["ampm"].lower().startswith("p")
            h = (h % 12) + (12 if pm else 0)
        try:
            g["dt"] = dt.datetime(y, mo, d, h, g["mi"], g["s"])
        except ValueError:
            g["dt"] = None
    return [g for g in grezzi if g["dt"]]


class Chat:
    def __init__(self, nome, txt, cartella):
        self.nome, self.txt, self.cartella = nome, txt, cartella
        self.file = {f.name: f for f in cartella.rglob("*") if f.is_file() and f != txt}


def nome_da_file(p):
    s = Path(p).stem
    for pref in ["WhatsApp Chat - ", "WhatsApp Chat with ", "WhatsApp-Chat mit ", "Chat WhatsApp con ",
                 "Chat di WhatsApp con ", "Chat WhatsApp - ", "Chat de WhatsApp con ", "Discussion WhatsApp avec "]:
        if s.lower().startswith(pref.lower()):
            return s[len(pref):].strip()
    return s


def trova_txt(cartella):
    c = list(cartella.rglob("_chat.txt"))
    if c:
        return c[0]
    candidati = sorted(cartella.rglob("*.txt"), key=lambda f: f.stat().st_size, reverse=True)
    for f in candidati:
        with open(f, encoding="utf-8", errors="replace") as fh:
            testa = [pulisci(fh.readline()) for _ in range(5)]
        if any(RX_IOS.match(r) or RX_AND.match(r) for r in testa):
            return f
    return None


def prepara_chat(inputs, tmp):
    espansi = []
    for i in inputs:
        trovati = sorted(glob.glob(str(Path(i).expanduser()))) if any(ch in i for ch in "*?[") else []
        espansi += trovati or [i]
    chats = []
    for n, i in enumerate(espansi):
        p = Path(i).expanduser()
        if p.is_file() and zipfile.is_zipfile(p):
            dest = Path(tmp) / f"chat{n}"
            print(f"Estraggo {p.name} …")
            with zipfile.ZipFile(p) as z:
                z.extractall(dest)
            txt, cartella, nome = trova_txt(dest), dest, nome_da_file(p)
        elif p.is_dir():
            txt, cartella, nome = trova_txt(p), p, nome_da_file(p)
        elif p.is_file() and p.suffix.lower() == ".txt":
            txt, cartella, nome = p, p.parent, nome_da_file(p)
        else:
            print(f"  ! salto '{p}': non è una chat esportata (.zip, .txt o cartella)", file=sys.stderr)
            continue
        if not txt:
            print(f"  ! in '{p.name}' non trovo il testo della chat", file=sys.stderr)
            continue
        if txt.name != "_chat.txt" and nome_da_file(txt) != txt.stem:
            nome = nome_da_file(txt)
        chats.append(Chat(nome, txt, cartella))
    return chats


def analizza(chat, mese_prima):
    messaggi = []
    for g in costruisci_date(leggi_righe(chat.txt), mese_prima):
        m = RX_MITTENTE.match(g["resto"])
        mitt, testo = (m.group(1).strip(), m.group(2)) if m else (None, g["resto"])
        allegati, omesso = [], False

        def prendi(match):
            nomef = match.group(1).strip()
            if nomef in chat.file:
                allegati.append(chat.file[nomef])
                return ""
            return match.group(0)

        testo = RX_ALLEG_IOS.sub(prendi, testo)
        testo = RX_ALLEG_AND.sub(prendi, testo)
        testo = RX_NOMEFILE.sub(lambda mt: prendi(re.match(r"(.*)", mt.group(0))), testo)
        testo = testo.strip()
        if RX_OMESSO.match(testo):
            testo, omesso = "", True
        elif g["sistema"] and not allegati:
            mitt = None
        messaggi.append({"dt": g["dt"], "da": mitt, "testo": testo, "allegati": allegati, "omesso": omesso})
    return messaggi


# ---------------------------------------------------------------- scrittura

CSS = """
:root{--carta:#fbf8f3;--inchiostro:#2b2622;--tenue:#8a7f74;--riga:#e6dfd5;--accento:#128c7e;--mio:#e3f3ea;--altro:#fff}
*{box-sizing:border-box}
body{margin:0;background:var(--carta);color:var(--inchiostro);font:17px/1.55 Georgia,"Iowan Old Style","Palatino Linotype",serif}
main{max-width:760px;margin:0 auto;padding:2rem 1.1rem 5rem}
a{color:var(--accento)}
.copertina{text-align:center;padding:4rem 0 2.5rem;border-bottom:1px solid var(--riga)}
.copertina h1{font-size:2.6rem;font-weight:normal;margin:0 0 .4rem}
.copertina .sotto{color:var(--tenue);font-style:italic;margin:0}
.copertina .numeri,.copertina .chi{font:14px/1.6 system-ui,sans-serif;color:var(--tenue);margin-top:1.2rem}
nav.indice{text-align:center;padding:1.5rem 0;font:15px/2 system-ui,sans-serif}
nav.indice a{display:inline-block;margin:0 .3rem;padding:0 .6rem;border:1px solid var(--riga);border-radius:99px;text-decoration:none}
nav.indice small{color:var(--tenue)}
section.anno>h2{font-size:2.1rem;font-weight:normal;margin:3.5rem 0 0;padding-bottom:.3rem;border-bottom:2px solid var(--accento)}
h3.mese{font:600 13px/1 system-ui,sans-serif;text-transform:uppercase;letter-spacing:.14em;color:var(--tenue);margin:2.4rem 0 .3rem}
.giorno{margin:1.4rem 0 1.8rem}
.giorno>h4{font:600 14px/1 system-ui,sans-serif;color:var(--inchiostro);margin:0 0 .7rem;padding:.45rem .8rem;background:#efe9e0;border-radius:99px;display:inline-block}
.msg{width:fit-content;min-width:6rem;max-width:82%;margin:.35rem 0;padding:.45rem .75rem .35rem;border-radius:12px;background:var(--altro);box-shadow:0 1px 1.5px rgba(0,0,0,.09);break-inside:avoid}
.msg.mio{margin-left:auto;background:var(--mio)}
.msg .da{font:600 13px/1.3 system-ui,sans-serif;margin-bottom:.15rem}
.msg p{margin:.1rem 0 .2rem;white-space:pre-wrap;overflow-wrap:anywhere}
.msg .ora{font:11px system-ui,sans-serif;color:var(--tenue);text-align:right}
.msg img,.msg video{display:block;max-width:100%;max-height:420px;border-radius:8px;margin:.3rem 0}
.msg audio{width:100%;margin:.3rem 0}
.msg .file{font:14px system-ui,sans-serif}
.msg .omesso{font:italic 13px system-ui,sans-serif;color:var(--tenue)}
.sistema{text-align:center;font:italic 13px/1.4 system-ui,sans-serif;color:var(--tenue);margin:.6rem auto;max-width:85%}
.solo-stampa{display:none}
footer{text-align:center;color:var(--tenue);font:13px system-ui,sans-serif;margin-top:4rem}
ul.chat{list-style:none;padding:0;font:16px/1.4 system-ui,sans-serif}
ul.chat li{padding:.9rem 0;border-bottom:1px solid var(--riga)}
ul.chat a{font:20px Georgia,serif;text-decoration:none}
ul.chat small{display:block;color:var(--tenue)}
@media print{
 body{background:#fff;font-size:10.5pt}
 main{max-width:none;padding:0}
 .copertina{padding-top:30vh;break-after:page;border:0}
 nav.indice{display:none}
 section.anno{break-before:page}
 a{color:inherit;text-decoration:none}
 video,audio{display:none}
 .solo-stampa{display:block;font:9pt system-ui,sans-serif;color:#777}
 .msg{box-shadow:none;border:.5pt solid #ddd}
}
"""
COLORI = ["#c0392b", "#2471a3", "#7d3c98", "#b9770e", "#1e8449", "#a04000", "#2e4053", "#c2185b", "#00838f", "#6d4c41"]


def pagina(titolo, corpo):
    return f"""<!DOCTYPE html>
<html lang="{LINGUA}"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{html.escape(titolo)}</title><style>{CSS}</style></head>
<body><main>{corpo}</main></body></html>"""


def testo_html(t):
    t = html.escape(t)
    return re.sub(r"(https?://[^\s<]+)", r'<a href="\1">\1</a>', t)


def copia(src, out, usati, cache):
    if src in cache:
        return cache[src]
    rel = Path("media") / src.name
    n = 1
    while rel.as_posix() in usati:
        rel = Path("media") / f"{src.stem}_{n}{src.suffix}"
        n += 1
    usati.add(rel.as_posix())
    (out / rel).parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(src, out / rel)
    cache[src] = rel.as_posix()
    return cache[src]


def allegato_html(rel, src):
    r = html.escape(rel)
    ext = src.suffix.lower()
    if ext in IMG_EXT:
        return f'<a href="{r}"><img loading="lazy" src="{r}" alt=""></a>'
    if ext in VIDEO_EXT:
        return f'<video controls preload="metadata" src="{r}"></video><p class="solo-stampa">▶ video: {r}</p>'
    if ext in AUDIO_EXT:
        return f'<audio controls preload="none" src="{r}"></audio><p class="solo-stampa">🎙 {T("vocale")}: {r}</p>'
    return f'<p class="file">📎 <a href="{r}">{html.escape(src.name)}</a></p>'


def scrivi_diario(chat, messaggi, out, io):
    out.mkdir(parents=True, exist_ok=True)
    mittenti = []
    for m in messaggi:
        if m["da"] and m["da"] not in mittenti:
            mittenti.append(m["da"])
    if io and io not in mittenti:  # "--io Anna" trova anche "Anna Rossi"
        simili = [x for x in mittenti if io.lower() in x.lower()]
        io = simili[0] if len(simili) == 1 else ""
    if not io and len(mittenti) == 2 and chat.nome in mittenti:  # chat a due: "io" è l'altro
        io = next(x for x in mittenti if x != chat.nome)
    colore = {n: COLORI[i % len(COLORI)] for i, n in enumerate(x for x in mittenti if x != io)}

    usati, cache, corpo, conteggio = set(), {}, [], {}
    anno = mese = giorno = None
    n_media = 0
    for m in messaggi:
        d = m["dt"]
        if d.year != anno:
            if giorno is not None:
                corpo.append("</div>")
            if anno is not None:
                corpo.append("</section>")
            anno, mese, giorno = d.year, None, None
            corpo.append(f'<section class="anno" id="a{d.year}"><h2>{d.year}</h2>')
        if d.month != mese:
            if giorno is not None:
                corpo.append("</div>")
                giorno = None
            mese = d.month
            corpo.append(f'<h3 class="mese">{nome_mese(d.month)} {d.year}</h3>')
        if d.date() != giorno:
            if giorno is not None:
                corpo.append("</div>")
            giorno = d.date()
            corpo.append(f'<div class="giorno"><h4>{data_lunga(d)}</h4>')
        conteggio[d.year] = conteggio.get(d.year, 0) + 1

        if m["da"] is None:
            corpo.append(f'<p class="sistema">{testo_html(m["testo"])}</p>')
            continue
        mio = m["da"] == io
        parti = [f'<div class="msg{" mio" if mio else ""}">']
        if not mio and len(mittenti) > 1:
            parti.append(f'<div class="da" style="color:{colore.get(m["da"], "#555")}">{html.escape(m["da"])}</div>')
        for src in m["allegati"]:
            parti.append(allegato_html(copia(src, out, usati, cache), src))
            n_media += 1
        if m["testo"]:
            parti.append(f"<p>{testo_html(m['testo'])}</p>")
        if m["omesso"]:
            parti.append(f'<p class="omesso">— {T("omesso")} —</p>')
        parti.append(f'<div class="ora">{d:%H:%M}</div></div>')
        corpo.append("".join(parti))
    if giorno is not None:
        corpo.append("</div>")
    if anno is not None:
        corpo.append("</section>")

    if messaggi:
        periodo = f'{T("dal")} {data_breve(messaggi[0]["dt"])} {T("al")} {data_breve(messaggi[-1]["dt"])}'
    else:
        periodo = T("nessuno")
    indice = " ".join(f'<a href="#a{y}">{y} <small>{n}</small></a>' for y, n in sorted(conteggio.items()))
    chi = ", ".join(html.escape(x) for x in mittenti)
    oggi = dt.date.today()
    testa = f"""<div class="copertina"><h1>{html.escape(chat.nome)}</h1>
<p class="sotto">{T("sotto")}</p>
<p class="numeri">{len(messaggi)} {T("messaggi")} · {n_media} {T("media")} · {periodo}</p>
<p class="chi">{T("partecipanti")}: {chi}</p></div>
<nav class="indice">{indice}</nav>"""
    (out / "diario.html").write_text(
        pagina(chat.nome, testa + "".join(corpo) + f'<footer>{T("creato")} {data_breve(oggi)}</footer>'),
        encoding="utf-8")
    return len(messaggi), n_media, periodo, io


def cartella_sicura(nome, usate):
    base = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", nome).strip(" .") or "chat"
    n, cand = 1, base
    while cand.lower() in usate:
        n += 1
        cand = f"{base} ({n})"
    usate.add(cand.lower())
    return cand


def main():
    global LINGUA
    ap = argparse.ArgumentParser(description="Trasforma le chat esportate da WhatsApp in diari HTML.")
    ap.add_argument("chat", nargs="+", help="chat esportate: file .zip, file .txt (con le foto nella stessa cartella) o cartelle")
    ap.add_argument("-o", "--output", default="Diario_WhatsApp", help="cartella da creare (default: Diario_WhatsApp)")
    ap.add_argument("--io", default="", help="il tuo nome come appare nella chat: i tuoi messaggi vanno a destra")
    ap.add_argument("--mese-prima", action="store_true", help="date all'americana (mese/giorno), se lo script sbaglia")
    ap.add_argument("--lingua", choices=["it", "en"], default="it", help="lingua del diario / diary language")
    a = ap.parse_args()
    LINGUA = a.lingua

    out = Path(a.output).expanduser()
    out.mkdir(parents=True, exist_ok=True)
    righe, usate = [], set()
    with tempfile.TemporaryDirectory() as tmp:
        chats = prepara_chat(a.chat, tmp)
        if not chats:
            sys.exit("Nessuna chat trovata.")
        for chat in chats:
            print(f"Chat: {chat.nome}")
            messaggi = analizza(chat, True if a.mese_prima else None)
            sotto = cartella_sicura(chat.nome, usate)
            n, nm, periodo, io = scrivi_diario(chat, messaggi, out / sotto, a.io)
            print(f"  {n} messaggi, {nm} allegati" + ("" if io else "  (usa --io \"Il tuo nome\" per mettere a destra i tuoi messaggi)"))
            righe.append((chat.nome, sotto, n, periodo))
    elenco = "".join(
        f'<li><a href="{html.escape(s)}/diario.html">{html.escape(nm)}</a><small>{n} {T("messaggi")} · {html.escape(p)}</small></li>'
        for nm, s, n, p in sorted(righe, key=lambda r: r[0].lower()))
    (out / "indice.html").write_text(pagina(T("indice"), f"""<div class="copertina"><h1>{T("indice")}</h1>
<p class="numeri">{len(righe)} {T("chat")}</p></div><ul class="chat">{elenco}</ul>"""), encoding="utf-8")
    print(f"\n✓ Fatto: apri {out / 'indice.html'}")


if __name__ == "__main__":
    main()
