from PIL import Image
from collections import deque

img = Image.open('Montaje Carpa La Espailla_preview.png').convert('RGB')
w, h = img.size
p = img.load()

# Frontera: lineas negras/oscuras del troquel
boundary = [[False]*w for _ in range(h)]
for y in range(h):
    for x in range(w):
        r,g,b = p[x,y]
        if r < 40 and g < 40 and b < 40:
            boundary[y][x] = True

mask = [[False]*w for _ in range(h)]

seeds = [
    (4200, 2100),  # cara superior
    (2350, 4150),  # cara izquierda
    (6100, 4150),  # cara derecha
    (4200, 6150),  # cara inferior
    (4200, 1460),  # faldon superior
    (1350, 4150),  # faldon izquierdo
    (7060, 4150),  # faldon derecho
    (4200, 7600),  # faldon inferior
]

for sx, sy in seeds:
    if sx < 0 or sy < 0 or sx >= w or sy >= h:
        continue
    if boundary[sy][sx] or mask[sy][sx]:
        continue
    q = deque([(sx, sy)])
    mask[sy][sx] = True
    while q:
        x, y = q.popleft()
        for nx, ny in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):
            if 0 <= nx < w and 0 <= ny < h and (not boundary[ny][nx]) and (not mask[ny][nx]):
                mask[ny][nx] = True
                q.append((nx, ny))

# Rellenar agujeros internos (logos negros dentro de paneles)
comp = [[not mask[y][x] for x in range(w)] for y in range(h)]
outside = [[False]*w for _ in range(h)]
q = deque()
for x in range(w):
    if comp[0][x]:
        outside[0][x]=True; q.append((x,0))
    if comp[h-1][x]:
        outside[h-1][x]=True; q.append((x,h-1))
for y in range(h):
    if comp[y][0] and not outside[y][0]:
        outside[y][0]=True; q.append((0,y))
    if comp[y][w-1] and not outside[y][w-1]:
        outside[y][w-1]=True; q.append((w-1,y))
while q:
    x,y = q.popleft()
    for nx, ny in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):
        if 0 <= nx < w and 0 <= ny < h and comp[ny][nx] and not outside[ny][nx]:
            outside[ny][nx] = True
            q.append((nx, ny))

for y in range(h):
    for x in range(w):
        if comp[y][x] and not outside[y][x]:
            mask[y][x] = True

out = Image.new('RGB', (w,h), (0,0,0))
o = out.load()
for y in range(h):
    row = mask[y]
    for x in range(w):
        if row[x]:
            o[x,y] = (255,255,255)

out.save('carpa-4caras-mask.png')
print('saved', w, h)
