import pymupdf as fitz, math, sys
src, out, cx, cy, r = sys.argv[1], sys.argv[2], float(sys.argv[4]), float(sys.argv[5]), float(sys.argv[3])
d = fitz.open(src); p = d[0]
ry = float(sys.argv[6]) if len(sys.argv) > 6 else r
k = ry / r
def band(x0, x1):
    pts = []
    N = 120
    for i in range(N + 1):  # metà superiore da sinistra a destra
        a = math.pi - math.pi * i / N
        x = cx + r * math.cos(a); y = cy - r * math.sin(a) * k
        if x0 <= x <= x1: pts.append((x, y))
    up = [(x1, cy - math.sqrt(max(0, r*r - (x1-cx)**2)) * k)]
    lo = []
    for i in range(N + 1):
        a = math.pi * i / N
        x = cx + r * math.cos(a); y = cy + r * math.sin(a) * k
        if x0 <= x <= x1: lo.append((x, y))
    poly = [(x0, cy - math.sqrt(max(0, r*r - (x0-cx)**2)) * k)] + pts + up + [(x1, cy + math.sqrt(max(0, r*r-(x1-cx)**2)) * k)] + lo + [(x0, cy + math.sqrt(max(0, r*r-(x0-cx)**2)) * k)]
    return poly
w = 2 * r / 3
sh = p.new_shape()
for i, col in enumerate(((0, .573, .275), (1, 1, 1), (.808, .169, .216))):
    x0 = cx - r + i * w; x1 = x0 + w
    sh.draw_polyline(band(x0, x1)); sh.finish(color=None, fill=col, closePath=True)
# il contorno nero a pennello va ridisegnato sopra
area = fitz.Rect(280, 30, 330, 75)
ring = [dr for dr in p.get_drawings() if dr['rect'].intersects(area) and dr['rect'].width < 60 and dr.get('fill') and max(dr['fill']) < 0.15]
for dr in ring:
    for it in dr['items']:
        if it[0] == 'l': sh.draw_line(it[1], it[2])
        elif it[0] == 'c': sh.draw_bezier(it[1], it[2], it[3], it[4])
        elif it[0] == 're': sh.draw_rect(it[1])
        elif it[0] == 'qu': sh.draw_quad(it[1])
    sh.finish(color=None, fill=dr['fill'], even_odd=dr.get('even_odd', False), closePath=dr.get('closePath', True), fill_opacity=dr.get('fill_opacity', 1))
print('tratti ridisegnati', len(ring))
sh.commit()
d.save(out, garbage=3, deflate=True)
fitz.open(out)[0].get_pixmap(dpi=500, clip=fitz.Rect(280, 30, 330, 75)).save('flag_it.png')
