"""Isolate the notebook asset from candidate-6 using flood-fill from the corners
(intelligent lasso). The flat cream background is made transparent; the notebook
paper, spiral, bookmarks, AND the green botanical sprig in the upper-right corner
are preserved. Edges are feathered with a gradient.

Approach:
1. Flood-fill from the 4 corners to find the connected background region.
2. Make that region transparent (alpha 0).
3. Preserve green botanical pixels (the sprig) even if they sit on the background.
4. Feather the alpha edge with a gradient so there's no harsh boundary.
"""
from PIL import Image
import numpy as np
from scipy import ndimage

SRC = r'C:\Users\danam\SGT-FANTASTIC-08-06-26\Local\PixieSprout\journal-candidate-6.png'
OUT = r'C:\Users\danam\SGT-FANTASTIC-08-06-26\Local\PixieSprout\assets\pixiesprout\notebook\journal-fullpage.png'

im = Image.open(SRC).convert('RGB')
a = np.array(im).astype(float)
w, h = im.size

# ---- Flood-fill background from the 4 corners ----
# A pixel is "background-like" if it's close to the flat cream AND not strongly
# green (so the botanical sprig survives). Use BFS.
bg = np.array([254, 245, 221], dtype=float)
dist = np.sqrt(((a - bg) ** 2).sum(axis=2))
# green-ness: G channel notably higher than R and B (botanical leaves)
green = (a[:, :, 1] - a[:, :, 0] > 12) & (a[:, :, 1] - a[:, :, 2] > 12)

# background candidate: close to cream AND not green
bg_cand = (dist < 30) & (~green)

# BFS flood fill from all 4 corners
from collections import deque
visited = np.zeros((h, w), dtype=bool)
q = deque()
for (cx, cy) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)]:
    if bg_cand[cy, cx]:
        visited[cy, cx] = True
        q.append((cx, cy))
while q:
    x, y = q.popleft()
    for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        nx, ny = x + dx, y + dy
        if 0 <= nx < w and 0 <= ny < h and not visited[ny, nx] and bg_cand[ny, nx]:
            visited[ny, nx] = True
            q.append((nx, ny))

# alpha: 0 for flood-filled background, 255 for notebook + botanicals
alpha = np.where(visited, 0.0, 1.0)

# Feather the alpha edge with a gradient (soft boundary)
alpha = ndimage.gaussian_filter(alpha, sigma=2.0)
# Re-saturate so the notebook body stays fully opaque
alpha = np.clip(alpha * 1.6, 0, 1)

rgba = np.dstack([a, alpha * 255]).astype(np.uint8)
out = Image.fromarray(rgba, 'RGBA')
out.save(OUT)
print('saved', OUT, out.size, 'mode', out.mode)
print('corner alpha:', out.getpixel((5, 5))[3])
print('center alpha:', out.getpixel((w // 2, h // 2))[3])
print('top-right sprig zone alpha (x=0.9w, y=0.05h):', out.getpixel((int(w*0.9), int(h*0.05)))[3])
# count transparent pixels
print('transparent fraction:', round((alpha < 0.5).mean(), 3))
