#!/usr/bin/env python3
"""Generate dashed card border texture for channel reorder mode focus indicator."""
from PIL import Image, ImageDraw
import math

# Final output dimensions (larger than poster 210x315 to surround it)
WIDTH, HEIGHT = 226, 331
BORDER = 3
RADIUS = 22
DASH_LEN = 12
GAP_LEN = 8
SCALE = 4  # Antialiasing

w, h = WIDTH * SCALE, HEIGHT * SCALE
r = RADIUS * SCALE
b = BORDER * SCALE
dash = DASH_LEN * SCALE
gap = GAP_LEN * SCALE

img = Image.new('RGBA', (w, h), (0, 0, 0, 0))

# Draw dashed rounded rectangle by creating a full border and masking with dashes
# Step 1: Create full solid border
border_img = Image.new('RGBA', (w, h), (0, 0, 0, 0))
border_draw = ImageDraw.Draw(border_img)
border_draw.rounded_rectangle([(0, 0), (w - 1, h - 1)], radius=r, fill=(255, 255, 255, 255))
border_draw.rounded_rectangle([(b, b), (w - 1 - b, h - 1 - b)], radius=r - b, fill=(0, 0, 0, 0))

# Step 2: Create dash mask along the perimeter
mask = Image.new('L', (w, h), 0)
mask_draw = ImageDraw.Draw(mask)

# Generate points along rounded rectangle perimeter
def rounded_rect_points(W, H, R, num_points=600):
    """Generate points along rounded rectangle perimeter."""
    points = []
    # Corner centers
    corners = [
        (R, R, 180, 270),           # top-left
        (W - R, R, 270, 360),       # top-right  
        (W - R, H - R, 0, 90),     # bottom-right
        (R, H - R, 90, 180),       # bottom-left
    ]
    # Straight edges + corners
    segments = []
    # Top edge
    segments.append(('line', R, 0, W - R, 0))
    # Top-right corner
    segments.append(('arc', W - R, R, R, 270, 360))
    # Right edge
    segments.append(('line', W, R, W, H - R))
    # Bottom-right corner
    segments.append(('arc', W - R, H - R, R, 0, 90))
    # Bottom edge
    segments.append(('line', W - R, H, R, H))
    # Bottom-left corner
    segments.append(('arc', R, H - R, R, 90, 180))
    # Left edge
    segments.append(('line', 0, H - R, 0, R))
    # Top-left corner
    segments.append(('arc', R, R, R, 180, 270))
    
    for seg in segments:
        if seg[0] == 'line':
            _, x1, y1, x2, y2 = seg
            length = math.sqrt((x2-x1)**2 + (y2-y1)**2)
            n = max(int(length / 2), 2)
            for i in range(n):
                t = i / n
                points.append((x1 + t*(x2-x1), y1 + t*(y2-y1)))
        else:
            _, cx, cy, radius, start_deg, end_deg = seg
            n = max(int(radius * abs(end_deg - start_deg) / 360 * 0.5), 8)
            for i in range(n):
                t = i / n
                angle = math.radians(start_deg + t * (end_deg - start_deg))
                points.append((cx + radius * math.cos(angle), cy + radius * math.sin(angle)))
    return points

# Get perimeter points
half_b = b // 2
pts = rounded_rect_points(w - 1, h - 1, r)

# Calculate cumulative distances
dists = [0]
for i in range(1, len(pts)):
    d = math.sqrt((pts[i][0]-pts[i-1][0])**2 + (pts[i][1]-pts[i-1][1])**2)
    dists.append(dists[-1] + d)

# Draw dashes along the perimeter
total_len = dists[-1]
cycle = dash + gap
pos = 0
while pos < total_len:
    # Find start and end indices for this dash
    dash_end = min(pos + dash, total_len)
    
    # Collect points in this dash segment
    dash_pts = []
    for i, d in enumerate(dists):
        if pos <= d <= dash_end:
            dash_pts.append(pts[i])
    
    # Draw thick line segments for the dash
    if len(dash_pts) >= 2:
        for i in range(len(dash_pts) - 1):
            x1, y1 = dash_pts[i]
            x2, y2 = dash_pts[i+1]
            mask_draw.line([(x1, y1), (x2, y2)], fill=255, width=b + 2)
    
    pos += cycle

# Step 3: Apply mask to border
result = Image.new('RGBA', (w, h), (0, 0, 0, 0))
result.paste(border_img, mask=mask)

# Downscale with antialiasing
result = result.resize((WIDTH, HEIGHT), Image.LANCZOS)
result.save('card_border.png', 'PNG')
print(f"Generated card_border.png ({WIDTH}x{HEIGHT}, dashed border={BORDER}px, radius={RADIUS}px)")
