"""Ricostruisce il regolamento in italiano: toglie il testo tedesco (e le icone in linea) dei blocchi elencati
in it.txt e ci scrive l'italiano, rimpicciolendo il testo se non ci sta.
Uso: python build.py [uscita.pdf]   (predefinito: ~/Desktop/PS_Regole_IT.pdf)"""
import pymupdf as fitz, json, re, statistics, sys, os

SRC = 'PS_Regeln_DE_piatnik.pdf'
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser('~/Desktop/PS_Regole_IT.pdf')
FD = 'fonts/'
# Semibold nel testo italiano diventa Bold: i sottoinsiemi Semibold hanno troppe poche lettere
FONTFILE = {k: FD + k + '_it.ttf' for k in ('B', 'Bi', 'M', 'Mi', 'BD', 'BDi', 'T')}
ALIAS = {'S': 'BD', 'Si': 'BDi'}
FOBJ = {k: fitz.Font(fontfile=v) for k, v in FONTFILE.items()}
hexc = lambda h: tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
# icone in linea: alias -> impronta (vedi view.txt)
ICON = {'E': 'c4a15aad', 'G': 'd65abc75', 'GR': '7385bfba'}
KEEP_ICONS = {'1c41b7c8', '16d7babb', 'f8300ee1', '969b944e', '1a30b2d9', '9ec76bf5', 'f3cc0c46'}
FNAME = {'Whitney-Book': 'B', 'Whitney-BookItalic': 'Bi', 'Whitney-Bold': 'BD', 'Whitney-BoldItalic': 'BDi',
         'Whitney-Semibold': 'BD', 'Whitney-SemiboldItalic': 'BDi', 'Whitney-Medium': 'M',
         'Whitney-MediumItalic': 'Mi', 'SaniretroRegular': 'T'}

data = json.load(open('tblocks.json'))
blocks = {b['id']: b for b in data['blocks']}
icons = data['icons']

def is_marker(r):
    t = r['t'].strip()
    if r['font'] == 'SaniretroRegular' and re.fullmatch(r'[A-D1-9]', t): return True
    if re.fullmatch(r'\d\.', t): return True
    if r['font'] == 'Whitney-Bold' and r['col'] == 'ffffff' and re.fullmatch(r'[A-D]', t): return True
    return False

def runs_of(ids):
    return [r for i in ids for l in blocks[i]['lines'] for r in l if r['t'].strip() and not is_marker(r)]

def rows_of(runs, gap=1e9):
    rows = []
    for r in sorted(runs, key=lambda r: (r['origin'][1], r['bbox'][0])):
        y = r['origin'][1]
        for row in rows:
            if abs(row['y'] - y) < 1.5 and r['bbox'][0] - row['x1'] < gap:
                row['x0'] = min(row['x0'], r['bbox'][0]); row['x1'] = max(row['x1'], r['bbox'][2])
                row['size'] = max(row['size'], r['size']); break
        else:
            lead_sp = len(r['t']) - len(r['t'].lstrip(' '))
            rows.append({'y': y, 'x0': r['bbox'][0] + lead_sp * r['size'] * 0.24, 'x1': r['bbox'][2], 'size': r['size'],
                         'font': r['font'], 'col': r['col']})
    rows.sort(key=lambda r: (round(r['y']), r['x0']))
    return rows

# ---------- testo italiano ----------
# {stile dimensione[:colore[/contorno]]}  _ davanti allo stile = sottolineato;  <E> <G> <h:impronta> icone;  @x: va a x
TOK = re.compile(r'\{(_?[A-Za-z]+)([\d.]+)(?::([0-9a-f]{6}(?:/[0-9a-f]{6})?))?\}|<([A-Za-z]+|h:[0-9a-f]{8})>|@(c?[\d.]+):|([^{<@]+|[<@])')
fk = lambda st: st.lstrip('_')

def parse(markup, defcol):
    """-> lista di paragrafi; ogni paragrafo è una lista di pezzi (tipo, stile, size, colore, testo/icona)"""
    paras = []
    for ptxt in markup.split('\\n'):
        pieces = []; st, sz, col = 'B', 10, defcol
        for m in TOK.finditer(ptxt):
            if m.group(1):
                st = m.group(1); st = st[:st.index(fk(st))] + ALIAS.get(fk(st), fk(st)); sz = float(m.group(2)); col = m.group(3) or defcol
            elif m.group(4):
                k = m.group(4); h = k[2:] if k.startswith('h:') else ICON[k]
                pieces.append(('icon', st, sz, col, h))
            elif m.group(5):
                v = m.group(5)
                pieces.append(('atc', st, sz, col, float(v[1:])) if v[0] == 'c' else ('at', st, sz, col, float(v)))
            elif m.group(6):
                # numeri attaccati alla parola (o all'icona) che segue
                t = re.sub(r'(?<![\w-])(\d+) ', '\\1\u00a0', m.group(6).replace('~', '\u00a0'))
                pieces.append(('text', st, sz, col, t))
        # un numero resta attaccato all'icona che lo segue ("2 <G>")
        for i, p in enumerate(pieces):
            if p[0] != 'icon': continue
            prev = [j for j in range(i) if pieces[j][0] == 'text']
            if not prev: continue
            before = ''.join(pieces[j][4] for j in prev)
            if re.search(r'\d[ \u00a0]$', before):
                j = prev[-1]; q = pieces[j]
                pieces[j] = q[:4] + (q[4][:-1] + '\u00a0',)
        paras.append(pieces)
    return paras

def piece_w(p, s):
    kind, st, sz, col, v = p
    if kind == 'text':
        w = FOBJ[fk(st)].text_length(v.replace('\u00a0', ' '), sz * s)
        return w + (len(v) * TRACK * sz * s if '/' in col else 0)
    if kind == 'icon': return icons[v]['w'] * s
    return 0

def words(pieces):
    """parole: si va a capo solo dopo uno spazio"""
    out, cur = [], []
    for p in pieces:
        if p[0] != 'text':
            cur.append(p); continue
        for part in re.findall(r'[^ ]+ *| +', p[4]):
            if not part.strip(' ') and not cur and out:   # spazio a inizio pezzo: resta alla parola prima
                out[-1].append(('text',) + p[1:4] + (part,)); continue
            cur.append(('text',) + p[1:4] + (part,))
            if part[-1] == ' ': out.append(cur); cur = []
    if cur: out.append(cur)
    return out

def line_w(pieces, s):
    w = 0
    for i, p in enumerate(pieces):
        if i == len(pieces) - 1 and p[0] == 'text': p = p[:4] + (p[4].rstrip(),)
        w += piece_w(p, s)
    return w

TRACK = 0.045  # spaziatura in più per il testo bianco col contorno (come "Weiß: Wohngebiete")
ICON_DY = {}  # impronta -> (alto dell'icona - linea di base) / dimensione del testo

def draw_pieces(page, pieces, x, y, s):
    for i, p in enumerate(pieces):
        kind, st, sz, col, v = p
        if kind == 'at': x = v; continue
        if kind == 'atc':
            seg = []
            for q in pieces[i + 1:]:
                if q[0] in ('at', 'atc'): break
                seg.append(q)
            x = v - line_w(seg, s) / 2; continue
        if kind == 'text':
            v = v.replace('\u00a0', ' ')
            f = fk(st); fill, _, stroke = col.partition('/')
            if stroke:
                for passn in (0, 1):
                    xx = x
                    for ch in v:
                        page.insert_text((xx, y), ch, fontsize=sz * s, fontname='f' + f, fontfile=FONTFILE[f],
                                         color=hexc(stroke if passn == 0 else fill), render_mode=1 - passn,
                                         border_width=0.12)
                        xx += FOBJ[f].text_length(ch, sz * s) + TRACK * sz * s
                x += piece_w(p, s); continue
            page.insert_text((x, y), v, fontsize=sz * s, fontname='f' + f, fontfile=FONTFILE[f], color=hexc(fill))
            if st.startswith('_'):
                w = FOBJ[f].text_length(v.rstrip(), sz * s)
                page.draw_line((x, y + 1.7 * s), (x + w, y + 1.7 * s), color=hexc(fill), width=0.5)
        else:
            I = icons[v]; w, h = I['w'] * s, I['h'] * s
            top = y + ICON_DY.get(v, -1.1) * sz * s
            page.insert_image(fitz.Rect(x, top, x + w, top + h), xref=I['xref'])
        x += piece_w(p, s)

def layout(paras, g, s):
    """righe -> [(pezzi, x, y)]; y dei capoversi agganciata a quella tedesca quando possibile"""
    rows, lead = g['rows'], g['lead'] * s
    out = []; y = None
    for pi, para in enumerate(paras):
        if y is None: y = rows[0]['y']
        else:
            y = y + lead + g['pgap'] * s
            if pi < len(g['pstarts']) and g['pstarts'][pi] > y and g['snap']: y = g['pstarts'][pi]
        cur = []
        def rowx(y):
            best = min(rows, key=lambda r: abs(r['y'] - y))
            if abs(best['y'] - y) < lead * 0.6 and (best is rows[0] or abs(best['x0'] - g['rx']) > 4):
                return best['x0']
            return g['rx']
        x = rowx(y)
        if pi == 0 and g['fx'] is not None: x = g['fx']
        if g['al'] == 'c': x = g['left']
        for wd in words(para):
            width = g['rightf'](y) - x
            if cur and line_w(cur + wd, s) > width:
                out.append((cur, x, y)); cur = []; y += lead
                x = rowx(y) if g['al'] != 'c' else g['left']
            cur += wd
        if cur: out.append((cur, x, y))
    return out

def geom(ids, opts, al):
    rows = rows_of(runs_of(ids))
    ys = [r['y'] for r in rows]
    diffs = [b - a for a, b in zip(ys, ys[1:])]
    ds = [d for d in diffs if d > 5]
    lead = statistics.median([d for d in ds if d < min(ds) * 1.25]) if ds else rows[0]['size'] * 1.4
    lead = float(opts.get('lead', lead))
    pstarts = [ys[0]] + [ys[i + 1] for i, d in enumerate(diffs) if d > lead * 1.3]
    if 'ps' in opts: pstarts = [float(v) for v in opts['ps'].split(',')]
    pg = [d - lead for d in diffs if d > lead * 1.3]
    xs = [r['x0'] for r in rows[1:]] or [rows[0]['x0']]
    rx = min(xs)
    g = dict(rows=rows, lead=lead, pstarts=pstarts, pgap=float(opts.get('pgap', statistics.median(pg) if pg else lead * 0.5)),
             rx=float(opts.get('rx', rx)), right=max(r['x1'] for r in rows) + 0.5,
             left=float(opts.get('l', min(r['x0'] for r in rows))), al=al, snap='nosnap' not in opts,
             fx=float(opts['fx']) if 'fx' in opts else None)
    # bordo destro a tratti: r=400:350,553 -> 400 fino a y=350, poi 553
    segs = []
    for part in str(opts.get('r', g['right'])).split(','):
        v, _, until = part.partition(':'); segs.append((float(v), float(until) if until else 1e9))
    g['right'] = max(v for v, u in segs)
    g['rightf'] = lambda y: next(v for v, u in segs if y <= u + 0.5)
    if al == 'c':
        g['left'] = float(opts.get('l', min(r['x0'] for r in rows)))
    return g

# ---------- lettura di it.txt ----------
entries = []
for n, line in enumerate(open('it.txt', encoding='utf-8')):
    if not line.strip() or line.startswith('#'): continue
    ids, mode, al, opts, txt = line.rstrip('\n').split('|', 4)
    ids = ids.split(',')
    for i in ids: assert i in blocks, (n + 1, i)
    o = {}
    for kv in filter(None, opts.split(';')):
        k, _, v = kv.partition('='); o[k.strip()] = v.strip() or True
    entries.append((ids, mode, al, o, txt))

doc = fitz.open(SRC)
H = doc[0].rect.height

# 1) icone in linea da togliere (si ridisegnano nel testo italiano)
taken = {i for e in entries for i in e[0]}
remove = {}
for h, I in icons.items():
    if h in KEEP_ICONS: continue
    for u in I['uses']:
        if u['block'] in taken: remove.setdefault(u['page'], []).append((h, u['bbox']))
# quota verticale delle icone rispetto alla linea di base, misurata sul tedesco
dys = {}
for h, I in icons.items():
    for u in I['uses']:
        if not u['block']: continue
        rows = rows_of(runs_of([u['block']]))
        if not rows: continue
        cy = (u['bbox'][1] + u['bbox'][3]) / 2
        r = min(rows, key=lambda r: abs(r['y'] - 3 - cy))
        dys.setdefault(h, []).append((u['bbox'][1] - r['y']) / r['size'])
for h, v in dys.items(): ICON_DY[h] = statistics.median(v)
CMRE = re.compile(rb'([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) cm\s*/(\w+) Do')
for pno, lst in remove.items():
    page = doc[pno]
    for xref in page.get_contents():
        s = doc.xref_stream(xref)
        def rep(m):
            a, b, c, d, e, f = (float(x) for x in m.groups()[:6])
            x0, y0 = e, H - (f + d)
            for h, bb in lst:
                if abs(bb[0] - x0) < 0.6 and abs(bb[1] - y0) < 0.6:
                    hits_list.append(bb); return m.group(0)[:m.start(7) - m.start(0) - 1]
            return m.group(0)
        hits_list = []
        new = CMRE.sub(rep, s)
        doc.update_stream(xref, new)
        if len(hits_list) != len(lst):
            missing = [bb for h, bb in lst if bb not in hits_list]
            print(f'pagina {pno + 1}: icone tolte {len(hits_list)} su {len(lst)}; non trovate: {missing}')

# 2) via le sottolineature e i contorni disegnati che accompagnavano il tedesco
CLEAR_ART = {5: [(227, 315.3, 269, 317.4), (425, 315.3, 446, 317.4)],   # p. 6: entweder / oder
             8: [(141.7, 672.3, 185, 674.4)],                             # p. 9: obersten
             1: [(88, 550, 190, 566)]}                                    # p. 2: contorno di "Weiß: Wohngebiete"
for pno, rects in CLEAR_ART.items():
    for r in rects: doc[pno].add_redact_annot(fitz.Rect(r), fill=False)
    doc[pno].apply_redactions(images=fitz.PDF_REDACT_IMAGE_NONE, graphics=fitz.PDF_REDACT_LINE_ART_REMOVE_IF_COVERED,
                              text=fitz.PDF_REDACT_TEXT_NONE)

# 3) via il tedesco, compresa la punteggiatura rimasta in blocchi senza lettere (".", "!" dopo un'icona)
orig = fitz.open(SRC)
for ids, mode, al, o, txt in entries:
    pno = blocks[ids[0]]['page']; rws = rows_of(runs_of(ids))
    gl, gr = min(r['x0'] for r in rws) - 5, max(r['x1'] for r in rws) + 30
    for b in orig[pno].get_text('dict')['blocks']:
        for l in b.get('lines', []):
            for sp in l['spans']:
                if not re.fullmatch(r'\s*[.,;:!?)]+\s*', sp['text']): continue
                if any(abs(sp['origin'][1] - r['y']) < 1.5 for r in rws) and gl < sp['bbox'][0] < gr:
                    rr = fitz.Rect(sp['bbox']); h = rr.height; rr.y0 += h * 0.25; rr.y1 -= h * 0.25
                    doc[pno].add_redact_annot(rr, fill=False)
for ids, mode, al, o, txt in entries:
    for r in runs_of(ids):
        rr = fitz.Rect(r['bbox']); h = rr.height; rr.y0 += h * 0.25; rr.y1 -= h * 0.25
        doc[blocks[ids[0]]['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)

# 4) l'italiano
report = []
SCALES = [1.0, .97, .94, .92, .9, .88, .86, .84, .82, .8, .78, .76, .74, .72, .7]
for ids, mode, al, o, txt in entries:
    page = doc[blocks[ids[0]]['page']]
    rs = runs_of(ids)
    cnt = {}
    for r in rs: cnt[r['col']] = cnt.get(r['col'], 0) + len(r['t'])
    defcol = o.get('col', max(cnt, key=cnt.get))
    if mode == 'lines':
        rows = rows_of(rs, gap=25)
        lead = (rows[-1]['y'] - rows[0]['y']) / (len(rows) - 1) if len(rows) > 1 else rows[0]['size'] * 1.2
        for i, m in enumerate(txt.split('||')):
            rdy = 0
            mm = re.match(r'\^(-?[\d.]+):', m)
            if mm: rdy = float(mm.group(1)); m = m[mm.end():]
            pieces = [p for para in parse(m, defcol) for p in para]
            if i < len(rows): row = rows[i]
            else: row = dict(rows[-1]); row['y'] = rows[-1]['y'] + lead * (i - len(rows) + 1)
            y = row['y'] + float(o.get('dy', 0)) + rdy
            x0, x1 = row['x0'], row['x1']
            if 'cx' in o: x0 = x1 = float(o['cx'])
            mw = float(o.get('mw', (x1 - x0) * 1.5 + 20))
            if any(p[0] in ('at', 'atc') for p in pieces):
                s = float(o.get('s', 1)); draw_pieces(page, pieces, x0, y, s); continue
            s = 1.0; w = line_w(pieces, s)
            if w > mw: s = mw / w; w = mw
            x = x0 if al == 'l' else (x1 - w if al == 'r' else (x0 + x1) / 2 - w / 2)
            draw_pieces(page, pieces, x, y, s)
            if s < 1: report.append((','.join(ids), len(rows), i + 1, s))
        continue
    g = geom(ids, o, al)
    paras = parse(txt, defcol)
    n0 = len(g['rows']); extra = float(o.get('x', 0))
    bottom = g['rows'][-1]['y'] + extra * g['lead'] + 0.5
    minS = float(o.get('min', 0.7))
    chosen = None
    for s in [s for s in SCALES if s >= minS]:
        L = layout(paras, g, s)
        if L[-1][2] <= bottom: chosen = (s, L); break
    if not chosen:
        s = max(minS, SCALES[-1]); chosen = (s, layout(paras, g, s))
        print(f'!! {",".join(ids)} non ci sta nemmeno a {s}: ultima riga a {chosen[1][-1][2]:.0f}, limite {bottom:.0f}')
    s, L = chosen
    for pieces, x, y in L:
        w = line_w(pieces, s)
        if al == 'c': x = (g['left'] + g['right']) / 2 - w / 2
        elif al == 'r': x = g['right'] - w
        draw_pieces(page, pieces, x, y, s)
    if s < 1 or len(L) != n0: report.append((','.join(ids), n0, len(L), s))

# Pagina 5: il testo delle 8 carte Iniziali e della carta di esempio (U-16) è testo vero, non disegno.
# Una riga per volta: (y della linea di base, x minima, x massima della carta, pezzi italiani, allineamento, larghezza max).
# "r" = allineato a destra sulla fine del tedesco, perché subito dopo c'è un'icona disegnata che non si sposta.
# U-13 è coperta da U-16: il suo testo non si vede e resta com'è.
CARTE_P5 = [
    (646.0, 270, 320, [('BD', 'Costruisci 1')], 'r', 40),
    (650.8, 270, 320, [('B', 'in una '), ('Bi', 'zona ricreativa')], 'c', 44),
    (646.0, 335, 382, [('BD', 'Costruisci 1')], 'r', 40),
    (650.8, 335, 382, [('B', 'in una '), ('Bi', 'zona residenziale')], 'c', 44),
    (643.6, 400, 447, [('BD', 'Costruisci 2')], 'r', 40),
    (648.4, 400, 447, [('B', 'su una casella in una')], 'c', 44),
    (653.2, 400, 447, [('Bi', 'zona commerciale')], 'c', 44),
    (643.6, 465, 512, [('BD', 'Costruisci 1')], 'r', 40),
    (648.4, 465, 512, [('B', 'in una '), ('Bi', 'zona industriale')], 'c', 44),
    (653.2, 465, 512, [('B', 'e '), ('BD', 'ricevi 1')], 'r', 40),
    (720.8, 300, 340, [('BD', 'Ricevi 1')], 'r', 40),
    (720.8, 365, 405, [('BD', 'Ricevi 1')], 'r', 40),
    (720.8, 430, 470, [('BD', 'Ricevi 1')], 'r', 40),
    (720.8, 495, 535, [('BD', 'Ricevi 1')], 'r', 40),
    (462.7, 355, 410, [('BD', 'Prendi 1')], 'r', 90),
    (474.7, 355, 380, [('B', 'gratis dal mercato Base')], 'c', 112),
    (486.7, 355, 400, [('B', 'e mettila in mano')], 'c', 112),
]
p5 = doc[4]
righe_p5 = []
for y0, xa, xb, pezzi, al, mw in CARTE_P5:
    sp = [sp for b in p5.get_text('dict')['blocks'] for l in b.get('lines', []) for sp in l['spans']
          if abs(sp['origin'][1] - y0) < 0.3 and xa <= sp['bbox'][0] <= xb and sp['text'].strip()]
    if not sp: sys.exit(f'pagina 5: niente testo a y={y0} fra x {xa} e {xb}')
    x0 = min(q['bbox'][0] for q in sp); x1 = max(q['bbox'][2] for q in sp); sz = sp[0]['size']
    col = '%06x' % sp[0]['color']
    for q in sp:
        r = fitz.Rect(q['bbox']); p5.add_redact_annot(fitz.Rect(r.x0, y0 - sz * 0.75, r.x1, y0 + sz * 0.05), fill=False)
    righe_p5.append((y0, x0, x1, sz, col, pezzi, al, mw))
p5.apply_redactions(images=fitz.PDF_REDACT_IMAGE_NONE, graphics=fitz.PDF_REDACT_LINE_ART_NONE)
# La redazione riscrive le forme XObject della pagina in copie nuove, e nelle copie le ombre con maschera morbida
# diventano nere (le strisce nere ai lati dei pannelli delle carte, già nella versione del 17/11). Le forme senza
# testo si rimettono com'erano nell'originale (stessa BBox), quelle con testo restano le copie ripulite.
src5 = fitz.open(SRC)
def forme(dd, pg):
    ris = dd.xref_get_key(pg.xref, 'Resources/XObject')[1]
    return dict(re.findall(r'/(\w+) (\d+) 0 R', ris))
def bbox(dd, x):
    m = re.search(r'/BBox\s*\[([^\]]+)\]', dd.xref_object(x, compressed=True)); return m and [round(float(v), 1) for v in m.group(1).split()]
orig_f = {}
for nome, x in forme(src5, src5[4]).items():
    x = int(x); o = src5.xref_object(x, compressed=True)
    if '/Subtype/Form' in o and b'BT' not in (src5.xref_stream(x) or b''): orig_f[str(bbox(src5, x))] = x
for nome, x in forme(doc, p5).items():
    x = int(x); o = doc.xref_object(x, compressed=True)
    if '/Subtype/Form' not in o or b'BT' in (doc.xref_stream(x) or b''): continue
    k = str(bbox(doc, x))
    if k in orig_f and orig_f[k] != x:
        doc.xref_set_key(p5.xref, f'Resources/XObject/{nome}', f'{orig_f[k]} 0 R')
for y0, x0, x1, sz, col, pezzi, al, mw in righe_p5:
    larg = sum(FOBJ[f].text_length(t, sz) for f, t in pezzi)
    k = min(1.0, mw / larg)
    larg *= k
    x = x1 - larg if al == 'r' else (x0 + x1) / 2 - larg / 2
    for f, t in pezzi:
        p5.insert_text((x, y0), t, fontsize=sz * k, fontname='f' + f, fontfile=FONTFILE[f], color=hexc(col))
        x += FOBJ[f].text_length(t, sz * k)

# il bollino della lingua a pagina 1: D -> I
p0 = doc[0]
for b in fitz.open(SRC)[0].get_text('dict')['blocks']:
    for l in b.get('lines', []):
        for sp in l['spans']:
            if sp['font'] == 'Mignon-Bold' and sp['text'].strip() == 'D':
                r = fitz.Rect(sp['bbox']); cx = (r.x0 + r.x1) / 2
                p0.add_redact_annot(r, fill=False)
                p0.apply_redactions(images=fitz.PDF_REDACT_IMAGE_NONE, graphics=fitz.PDF_REDACT_LINE_ART_NONE)
                w = fitz.get_text_length('I', fontname='tibo', fontsize=sp['size'])
                p0.insert_text((cx - w / 2, sp['origin'][1]), 'I', fontname='tibo', fontsize=sp['size'], color=(1, 1, 1))

# La redazione di PyMuPDF riscrive i contenuti e toglie "0 scn" dopo "/CS0 cs" credendolo il colore predefinito.
# Ma CS0 è una Separation (/All) e dopo "cs" il colore iniziale è 1, cioè nero pieno: così le ombre e i pannelli
# bianchi delle carte (p. 5 e altre) diventavano neri. Si rimette "0 scn" dove manca.
CSFIX = re.compile(rb'(/CS\d+ cs)(?!\s*[-\d.]+(?:\s+[-\d.]+)*\s*scn)')
fixed = 0
for x in range(1, doc.xref_length()):
    try:
        if not doc.xref_is_stream(x): continue
        o = doc.xref_object(x, compressed=True)
        if '/Subtype/Image' in o or '/FontFile' in o or '/Length1' in o: continue
        st = doc.xref_stream(x)
    except Exception:
        continue
    if not st or b' cs' not in st: continue
    new, n = CSFIX.subn(rb'\1 0 scn', st)
    if n: doc.update_stream(x, new); fixed += n
print('colore delle Separation ripristinato in', fixed, 'punti')

doc.subset_fonts()
doc.save(OUT, garbage=3, deflate=True)
for r in report: print('blocco %s: righe %d -> %d, scala %.2f' % r)
print('salvato', OUT)
