#!/usr/bin/env python3
"""BUG-HUNT - lamp bleeds through text for depth, stronger gradient over board."""

from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageChops
import numpy as np
import os

orig = Image.open("/root/.openclaw/workspace/output/bug-hunt-evidence-board-v2-2.png").convert("RGBA")
w, h = orig.size

font_path = "/tmp/clash-display/ClashDisplay_Complete/Fonts/OTF/ClashDisplay-Bold.otf"
text = "BUG-HUNT"

# Size to span ~78% with moderate tracking
target_width = int(w * 0.78)
best_size = 80
for size in range(60, 200, 5):
    font = ImageFont.truetype(font_path, size)
    tracking = int(size * 0.12)
    total = sum(font.getbbox(c)[2] - font.getbbox(c)[0] for c in text) + tracking * (len(text) - 1)
    if total <= target_width:
        best_size = size
    else:
        break

font = ImageFont.truetype(font_path, best_size)
print(f"Font size: {best_size}")

tracking = int(best_size * 0.12)
char_widths = [font.getbbox(c)[2] - font.getbbox(c)[0] for c in text]
total_text_w = sum(char_widths) + tracking * (len(text) - 1)
start_x = (w - total_text_w) // 2
y_pos = int(h * 0.08)

# ---- APPROACH: Layer compositing ----
# 1. Darken a band at the top for text readability (especially over corkboard)
# 2. Draw text
# 3. Use original bright lamp pixels to "burn through" the text

# Step 1: Create darkened base - stronger over right side (corkboard area)
dark_overlay = Image.new("RGBA", (w, h), (0, 0, 0, 0))
dd = ImageDraw.Draw(dark_overlay)
text_h = font.getbbox(text)[3] - font.getbbox(text)[1]
band_top = y_pos - 20
band_bottom = y_pos + text_h + 20

for y in range(max(0, band_top - 30), min(h, band_bottom + 40)):
    # Fade in/out vertically
    if y < band_top:
        vert_alpha = (y - (band_top - 30)) / 30
    elif y > band_bottom:
        vert_alpha = 1 - (y - band_bottom) / 40
    else:
        vert_alpha = 1.0
    
    for x_px in range(w):
        # Stronger on right (corkboard) side
        horiz_factor = 0.3 + 0.5 * (x_px / w)  # 0.3 on left, 0.8 on right
        alpha = int(100 * vert_alpha * horiz_factor)
        dd.point((x_px, y), fill=(5, 10, 25, alpha))

darkened = Image.alpha_composite(orig, dark_overlay)

# Step 2: Draw text with drop shadow onto darkened image
result = darkened.copy()
# Shadow
shadow = Image.new("RGBA", (w, h), (0, 0, 0, 0))
sd = ImageDraw.Draw(shadow)
x = start_x
for i, c in enumerate(text):
    sd.text((x + 2, y_pos + 3), c, font=font, fill=(0, 0, 0, 200))
    x += char_widths[i] + tracking
shadow = shadow.filter(ImageFilter.GaussianBlur(radius=6))
result = Image.alpha_composite(result, shadow)

# White text
text_img = Image.new("RGBA", (w, h), (0, 0, 0, 0))
td = ImageDraw.Draw(text_img)
x = start_x
for i, c in enumerate(text):
    td.text((x, y_pos), c, font=font, fill=(255, 255, 255, 255))
    x += char_widths[i] + tracking

result = Image.alpha_composite(result, text_img)

# Step 3: Lamp burn-through - where original image was very bright (lamp),
# blend original back on top to create "lamp in front of text" effect
orig_arr = np.array(orig).astype(float)
result_arr = np.array(result).astype(float)
brightness = np.mean(orig_arr[:,:,:3], axis=2)

# Only in the lamp area (upper-left)
lamp_blend = np.zeros((h, w), dtype=float)
for y_c in range(int(h * 0.45)):
    for x_c in range(int(w * 0.30)):
        b = brightness[y_c, x_c]
        if b > 100:
            lamp_blend[y_c, x_c] = min(1.0, (b - 100) / 100)

# Smooth
lb_img = Image.fromarray((lamp_blend * 255).astype(np.uint8))
lb_img = lb_img.filter(ImageFilter.GaussianBlur(radius=6))
lamp_blend = np.array(lb_img).astype(float) / 255.0

# Apply: blend original lamp pixels back over the text
for c_idx in range(3):
    result_arr[:,:,c_idx] = (
        lamp_blend * orig_arr[:,:,c_idx] + 
        (1 - lamp_blend) * result_arr[:,:,c_idx]
    )

final = Image.fromarray(result_arr.astype(np.uint8))
out = "/root/.openclaw/workspace/output/bug-hunt-evidence-board-final.png"
final.convert("RGB").save(out, "PNG")
print(f"Saved: {out} ({os.path.getsize(out)} bytes)")
