#!/usr/bin/env python3
"""BUG-HUNT text composited behind the lamp with better integration."""

from PIL import Image, ImageDraw, ImageFont, ImageFilter
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: span ~78% width with 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.15)
    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

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

tracking = int(best_size * 0.15)
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)  # slightly lower for breathing room

# Step 1: Add a subtle dark gradient at the top to help text readability
gradient = Image.new("RGBA", (w, h), (0, 0, 0, 0))
grad_draw = ImageDraw.Draw(gradient)
# Dark vignette at top - fades from ~60% opacity to 0% over top 35%
for y in range(int(h * 0.35)):
    alpha = int(130 * (1 - y / (h * 0.35)))
    grad_draw.line([(0, y), (w, y)], fill=(10, 15, 30, alpha))

darkened = Image.alpha_composite(orig, gradient)

# Step 2: Draw text with shadow
shadow_layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
sd = ImageDraw.Draw(shadow_layer)
x = start_x
for i, c in enumerate(text):
    sd.text((x + 3, y_pos + 3), c, font=font, fill=(0, 0, 0, 180))
    x += char_widths[i] + tracking
shadow_layer = shadow_layer.filter(ImageFilter.GaussianBlur(radius=5))

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

comp = Image.alpha_composite(darkened, shadow_layer)
comp = Image.alpha_composite(comp, text_layer)

# Step 3: Lamp masking - restore original pixels where lamp is bright
# Be more aggressive with the mask
orig_arr = np.array(orig).astype(float)
brightness = np.mean(orig_arr[:,:,:3], axis=2)

# Create mask for lamp area (upper-left quadrant)
mask = np.zeros((h, w), dtype=float)

# The lamp bulb and arm area - upper left
for y_c in range(int(h * 0.50)):
    for x_c in range(int(w * 0.28)):
        b = brightness[y_c, x_c]
        if b > 80:  # Lower threshold to catch more of the lamp
            mask[y_c, x_c] = min(1.0, (b - 80) / 80)

# Also catch the very bright lamp glow
for y_c in range(int(h * 0.50)):
    for x_c in range(int(w * 0.35)):
        b = brightness[y_c, x_c]
        if b > 150:
            mask[y_c, x_c] = min(1.0, (b - 100) / 55)

# Blur mask for smooth edges
mask_img = Image.fromarray((mask * 255).astype(np.uint8))
mask_img = mask_img.filter(ImageFilter.GaussianBlur(radius=4))
mask = np.array(mask_img).astype(float) / 255.0

# Blend: where mask is high, use original (lamp in front); elsewhere use composited
comp_arr = np.array(comp).astype(float)
orig_arr2 = np.array(orig).astype(float)

for c_idx in range(4):
    comp_arr[:,:,c_idx] = mask * orig_arr2[:,:,c_idx] + (1 - mask) * comp_arr[:,:,c_idx]

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