import pymupdf as fitz, json, re, statistics, sys

SRC = 'base_it.pdf'
OUT = sys.argv[1] if len(sys.argv) > 1 else 'out.pdf'
FD = 'fonts/'
FONTS = {
    'F': FD + 'SLACPI_FuturaBT-Light_2035_it.ttf',
    'Fi': FD + 'DMIQNM_FuturaBT-LightItalic_2032_it.ttf',
    'P': FD + 'GYANDG_ProtestRevolution-Regular_1983_it.ttf',
    'Ai': FD + 'DULLNM_AlegreyaSans-Italic_1923_it.ttf',
    'K': FD + 'kanji_tt.ttf',
}
FOBJ = {k: fitz.Font(fontfile=v) for k, v in FONTS.items()}
hexc = lambda h: tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
BLACK = '000000'
# stile: (font, colore, (colore contorno, spessore relativo alla dimensione) o None)
STY = {
    'F': ('F', BLACK, None), 'Fi': ('Fi', BLACK, None), 'P': ('P', BLACK, None), 'Ai': ('Ai', BLACK, None),
    'H': ('P', BLACK, ('fdf8ee', 2 / 14)),
    'FIRE': ('P', 'ea8725', ('ffffff', 0.2)), 'FIREN': ('P', 'ea8725', None),
    'WATER': ('P', '2f9dd7', ('ffffff', 0.2)),
    'KF': ('K', 'ea8725', ('ffffff', 0.2)), 'KW': ('K', '2f9dd7', ('ffffff', 0.2)),
}

def parse(markup):
    """'{F10}testo {FIRE10}Fuoco' -> lista di paragrafi, ognuno lista di (stile, size, testo)"""
    paras = []
    for ptxt in markup.split('\\n'):
        runs = []
        for m in re.finditer(r'\{([A-Za-z]+)([\d.]+)\}([^{]*)', ptxt):
            if m.group(3):
                runs.append((m.group(1), float(m.group(2)), m.group(3)))
        paras.append(runs)
    return paras

def tokens(runs):
    """spezza in parole (si va a capo solo dopo uno spazio); ogni parola = lista di pezzi"""
    toks, cur = [], []
    for st, sz, txt in runs:
        for part in re.findall(r'\S+\s*|\s+', txt):
            cur.append((st, sz, part))
            if part[-1].isspace():
                toks.append(cur); cur = []
    if cur: toks.append(cur)
    return toks

def wlen(pieces, s, strip=False):
    w = 0
    for i, (st, sz, t) in enumerate(pieces):
        if strip and i == len(pieces) - 1: t = t.rstrip()
        w += FOBJ[STY[st][0]].text_length(t, sz * s)
    return w

def wrap(paras, s, width_first, width_rest):
    lines = []  # (pezzi, nuovo_paragrafo)
    for pi, runs in enumerate(paras):
        cur = []; first_of_para = True
        for tok in tokens(runs):
            maxw = width_first if not lines and not cur else width_rest
            if cur and wlen(cur + tok, s, strip=True) > maxw:
                lines.append((cur, first_of_para and pi > 0)); first_of_para = False if lines[-1] else first_of_para
                first_of_para = False
                cur = list(tok)
            else:
                cur += tok
        if cur: lines.append((cur, first_of_para and pi > 0))
    return lines

def draw_line(page, pieces, x, y, s):
    # prima i contorni, poi il riempimento
    for passn in (0, 1):
        xx = x
        for st, sz, t in pieces:
            f, col, stroke = STY[st]
            size = sz * s
            if passn == 0 and stroke:
                page.insert_text((xx, y), t, fontsize=size, fontname='f' + f, fontfile=FONTS[f],
                                 color=hexc(stroke[0]), render_mode=1, border_width=stroke[1])
            if passn == 1:
                page.insert_text((xx, y), t, fontsize=size, fontname='f' + f, fontfile=FONTS[f],
                                 color=hexc(col), render_mode=0)
            xx += FOBJ[f].text_length(t, size)

def orig_lines(b):
    """righe originali per linea di base (spezzate se sulla stessa riga ci sono due testi lontani): [(y, x0, x1, size)]"""
    runs = []
    for l in b['lines']:
        for r in l:
            if r['t'].strip(): runs.append((round(r['origin'][1], 0), r['bbox'][0], r['bbox'][2], r['size']))
    runs.sort(key=lambda r: (r[0], r[1]))
    rows = []
    for y, x0, x1, sz in runs:
        for row in rows:
            if abs(row[0] - y) < 1.5 and x0 - row[2] < 40 and x1 - row[1] > -40:
                row[1] = min(row[1], x0); row[2] = max(row[2], x1); row[3] = max(row[3], sz); break
        else:
            rows.append([y, x0, x1, sz])
    rows.sort(key=lambda r: (r[0], r[1]))
    return [tuple(r) for r in rows]

def align_of(ol):
    if len(ol) < 2: return 'l'
    sx0 = max(o[1] for o in ol) - min(o[1] for o in ol)
    sx1 = max(o[2] for o in ol) - min(o[2] for o in ol)
    sc = max((o[1] + o[2]) / 2 for o in ol) - min((o[1] + o[2]) / 2 for o in ol)
    best = min((sx0, 'l'), (sx1, 'r'), (sc, 'c'))
    return best[1]

blocks = {b['id']: b for b in json.load(open('tblocks.json'))}
tr = {}
for line in open('it.txt', encoding='utf-8'):
    if not line.strip() or line.startswith('#'): continue
    bid, mode, al, txt = line.rstrip('\n').split('|', 3)
    tr[bid] = (mode, al, txt)

missing = [k for k in tr if k not in blocks]
assert not missing, missing


GROUPS = [(['6.35', '6.36'], 372)]
MAXW = {'8.21': 126, '8.22': 126, '8.23': 120, '8.24': 120, '8.31': 126, '8.32': 126, '8.33': 118, '8.34': 118, '8.25': 128, '8.26': 120}
ROOM = {'7.30': 3}
IMGS = {}
GROUPED = {i for ids, _ in GROUPS for i in ids}
ALLB = json.load(open('blocks.json'))

def geom(b, al):
    ol = orig_lines(b)
    bx0, by0, bx1, by1 = b['bbox']
    n0 = len(ol)
    if n0 > 1:
        diffs = [ol[i + 1][0] - ol[i][0] for i in range(n0 - 1)]
        lead = statistics.median(diffs)
        gap = max(0, max(diffs) - lead) if max(diffs) > lead * 1.25 else 0
    else:
        lead = ol[0][3] * 1.2; gap = 0
    fx = ol[0][1]; rx = min(o[1] for o in ol[1:]) if n0 > 1 else fx
    if al == 'c': fx = rx = bx0
    right = bx1 + 0.5
    return dict(n0=n0, lead=lead, gap=gap, fx=fx, rx=rx, wf=right - fx, wr=right - rx, y0=ol[0][0],
                ylast=ol[-1][0], bx0=bx0, bx1=bx1)

def room_below(b):
    if b['id'] in ROOM: return ROOM[b['id']]
    pg = b['id'].split('.')[0]; bx0, by0, bx1, by1 = b['bbox']
    best = 496 - 28 - by1
    for r in IMGS.get(int(pg) - 1, []):
        ox0, oy0, ox1, oy1 = r
        ov = min(bx1, ox1) - max(bx0, ox0)
        if ov > 0.3 * min(bx1 - bx0, ox1 - ox0) and oy0 >= by1 - 1 and (oy1 - oy0) < 300:
            best = min(best, oy0 - by1)
    for o in ALLB:
        if o['id'].split('.')[0] != pg or o['id'] == b['id']: continue
        ox0, oy0, ox1, oy1 = o['bbox']
        ov = min(bx1, ox1) - max(bx0, ox0)
        if ov <= 0.3 * min(bx1 - bx0, ox1 - ox0): continue
        if oy0 >= by1 - 1:
            best = min(best, oy0 - by1)
    return best

def draw_flow(page, L, g, s, ystart, al):
    y = ystart
    for i, (pieces, newpara) in enumerate(L):
        if i > 0:
            y += g['lead'] * s + (g['gap'] * s if newpara else 0)
        w = wlen(pieces, s, strip=True)
        if al == 'c': x = (g['bx0'] + g['bx1']) / 2 - w / 2
        else: x = g['fx'] if i == 0 else g['rx']
        draw_line(page, pieces, x, y, s)

doc = fitz.open(SRC)
for _i, _p in enumerate(doc): IMGS[_i] = [tuple(im['bbox']) for im in _p.get_image_info()]
# 1) togliere il testo inglese
for bid, (mode, al, txt) in tr.items():
    b = blocks[bid]; page = doc[b['page']]
    for r in b['rects']:
        rr = fitz.Rect(r); h = rr.height
        rr.y0 += h * 0.25; rr.y1 -= h * 0.25
        page.add_redact_annot(rr, fill=False)
for page in doc:
    page.apply_redactions(images=fitz.PDF_REDACT_IMAGE_NONE, graphics=fitz.PDF_REDACT_LINE_ART_NONE,
                          text=fitz.PDF_REDACT_TEXT_REMOVE)

# 2) scrivere l'italiano
report = []
for bid, (mode, al, txt) in tr.items():
    b = blocks[bid]; page = doc[b['page']]
    ol = orig_lines(b)
    bx0, by0, bx1, by1 = b['bbox']
    if al == 'auto': al = align_of(ol)
    if mode == 'lines':
        mine = txt.split('||')
        lead = (ol[-1][0] - ol[0][0]) / (len(ol) - 1) if len(ol) > 1 else ol[0][3] * 1.2
        for i, m in enumerate(mine):
            pieces = [p for para in parse(m) for p in para]
            if i < len(ol): y, x0, x1, _ = ol[i]
            else: y = ol[-1][0] + lead * (i - len(ol) + 1); x0, x1 = ol[-1][1], ol[-1][2]
            s = 1.0
            w = wlen(pieces, s, strip=True)
            maxw = MAXW.get(bid, page.rect.width - 24)
            if w > maxw: s = maxw / w; w = maxw
            x = x0 if al == 'l' else (x1 - w if al == 'r' else (x0 + x1) / 2 - w / 2)
            draw_line(page, pieces, x, y, s)
        continue
    # flow
    if bid in GROUPED: continue
    paras = parse(txt)
    g = geom(b, al)
    n0, lead = g['n0'], g['lead']
    room = room_below(b)
    maxextra = max(0, int((room - 1) // lead))
    chosen = None
    for s in (1.0, .97, .94, .92):
        L = wrap(paras, s, g['wf'], g['wr'])
        if len(L) <= n0: chosen = (s, L); break
    if not chosen:
        for s in (1.0, .97, .94, .92, .9, .88, .86, .84, .82):
            L = wrap(paras, s, g['wf'], g['wr'])
            if len(L) <= n0 + maxextra: chosen = (s, L); break
    if not chosen:
        s = .82; chosen = (s, wrap(paras, s, g['wf'], g['wr']))
    s, L = chosen
    report.append((bid, n0, len(L), s))
    draw_flow(page, L, g, s, g['y0'], al)

# gruppi di blocchi impaginati uno sotto l'altro (i passi della preparazione)
for ids, bottom in GROUPS:
    bl = [blocks[i] for i in ids]; page = doc[bl[0]['page']]
    gs_ = [geom(b, tr[b['id']][1]) for b in bl]
    for s in (1.0, .97, .94, .92, .9, .88, .86, .84, .82, .8):
        Ls = [wrap(parse(tr[b['id']][2]), s, g['wf'], g['wr']) for b, g in zip(bl, gs_)]
        y = gs_[0]['y0']; ys = []
        for i, (L, g) in enumerate(zip(Ls, gs_)):
            if i > 0:
                prev = gs_[i - 1]
                y = y + (g['y0'] - prev['ylast']) * s
            ys.append(y)
            y = y + (len(L) - 1) * g['lead'] * s
        if y <= bottom: break
    for b, L, g, yy in zip(bl, Ls, gs_, ys):
        report.append((b['id'], g['n0'], len(L), s))
        draw_flow(page, L, g, s, yy, tr[b['id']][1])

doc.save(OUT, garbage=3, deflate=True)
for r in report:
    if r[2] != r[1] or r[3] < 1: print('blocco %s: righe %d -> %d, scala %.2f' % r)
print('salvato', OUT)
