#!/usr/bin/env python3
"""Add BUG-HUNT text with lamp masking so text goes BEHIND the lamp."""

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

# Load original image
orig = Image.open("/root/.openclaw/workspace/output/bug-hunt-evidence-board-v2-2.png").convert("RGBA")
w, h = orig.size
print(f"Image size: {w}x{h}")

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

# Find good size - span ~85% width with tracking
target_width = int(w * 0.82)
best_size = 80
for size in range(60, 200, 5):
    font = ImageFont.truetype(font_path, size)
    bbox = font.getbbox(text)
    text_w = bbox[2] - bbox[0]
    tracking = int(size * 0.2)
    total_w = text_w + tracking * (len(text) - 1)
    if total_w <= target_width:
        best_size = size
    else:
        break

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

# Calculate positions
tracking = int(best_size * 0.2)
chars = list(text)
char_widths = []
for c in chars:
    bbox = font.getbbox(c)
    char_widths.append(bbox[2] - bbox[0])
total_text_w = sum(char_widths) + tracking * (len(chars) - 1)
start_x = (w - total_text_w) // 2
y_pos = int(h * 0.06)

# Step 1: Create shadow layer
shadow_layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
shadow_draw = ImageDraw.Draw(shadow_layer)
x = start_x
for i, c in enumerate(chars):
    shadow_draw.text((x + 3, y_pos + 3), c, font=font, fill=(0, 0, 0, 150))
    x += char_widths[i] + tracking
# Blur the shadow
shadow_layer = shadow_layer.filter(ImageFilter.GaussianBlur(radius=4))

# Step 2: Create text layer (white)
text_layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
text_draw = ImageDraw.Draw(text_layer)
x = start_x
for i, c in enumerate(chars):
    text_draw.text((x, y_pos), c, font=font, fill=(255, 255, 255, 245))
    x += char_widths[i] + tracking

# Step 3: Composite - original + shadow + text
comp = Image.alpha_composite(orig, shadow_layer)
comp = Image.alpha_composite(comp, text_layer)

# Step 4: Create a mask from the lamp area of the original image
# The lamp is in the upper-left area. We need to detect bright lamp pixels
# and use them to mask the text (so lamp appears in front of text)
# 
# Strategy: compare brightness of original vs the dark background
# The lamp + its arm are the brightest elements in the upper portion
orig_arr = np.array(orig)
# Focus on upper 40% where the lamp arm and bulb are
upper = orig_arr[:int(h*0.4), :int(w*0.35)]  # upper-left quadrant

# Create lamp mask: pixels that are notably bright (lamp glow + arm)
# Use the original image - anything significantly brighter than the dark BG
brightness = np.mean(orig_arr[:,:,:3], axis=2)  # average RGB

# The dark background is roughly < 60 brightness, lamp/arm > 100
lamp_mask = Image.new("L", (w, h), 0)
lamp_arr = np.array(lamp_mask)

# Mark bright pixels in the upper portion as "lamp" (should be in front of text)
# Be selective: only the lamp bulb glow and arm, not the whole scene
for y_check in range(int(h * 0.45)):
    for x_check in range(int(w * 0.30)):
        if brightness[y_check, x_check] > 120:
            lamp_arr[y_check, x_check] = 255

lamp_mask = Image.fromarray(lamp_arr)
# Slight blur to soften the mask edges
lamp_mask = lamp_mask.filter(ImageFilter.GaussianBlur(radius=3))

# Step 5: Where lamp_mask is white, use original pixels instead of composited
# This makes the lamp appear IN FRONT of the text
final = comp.copy()
final_arr = np.array(final)
orig_arr_rgba = np.array(orig)
mask_arr = np.array(lamp_mask) / 255.0

for c_idx in range(4):
    final_arr[:,:,c_idx] = (
        mask_arr * orig_arr_rgba[:,:,c_idx] + 
        (1 - mask_arr) * final_arr[:,:,c_idx]
    ).astype(np.uint8)

final = Image.fromarray(final_arr)

# Save
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)")
