"""
Visible watermark overlay for clawID.

Renders semi-transparent text (with optional shadow for readability)
at a configurable position on the image.
"""

import os
from PIL import Image, ImageDraw, ImageFont


# Common system font paths — tried in order, first match wins
_FONT_CANDIDATES = [
    # macOS
    '/System/Library/Fonts/Helvetica.ttc',
    '/System/Library/Fonts/Arial.ttf',
    '/Library/Fonts/Arial.ttf',
    # Linux
    '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
    '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf',
    '/usr/share/fonts/truetype/freefont/FreeSans.ttf',
    # Windows
    'C:/Windows/Fonts/arial.ttf',
    'C:/Windows/Fonts/segoeui.ttf',
]

_POSITIONS = {
    'top-left',
    'top-right',
    'bottom-left',
    'bottom-right',
    'center',
}


def embed_visible(
    image: Image.Image,
    text: str,
    position: str = 'bottom-right',
    opacity: float = 0.6,
    font_size: int = 20,
    padding: int = 12,
) -> Image.Image:
    """
    Add a visible text watermark to an image.

    Args:
        image:     RGB PIL Image
        text:      watermark text to display
        position:  one of top-left / top-right / bottom-left / bottom-right / center
        opacity:   text opacity 0.0–1.0  (default 0.6)
        font_size: font size in pixels   (default 20)
        padding:   distance from image edge in pixels (default 12)

    Returns:
        Watermarked RGB PIL Image
    """
    if position not in _POSITIONS:
        raise ValueError(f"position must be one of {sorted(_POSITIONS)}, got '{position}'")
    if not 0.0 <= opacity <= 1.0:
        raise ValueError(f"opacity must be between 0.0 and 1.0, got {opacity}")

    img = image.convert('RGBA')
    overlay = Image.new('RGBA', img.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)

    font = _load_font(font_size)

    # Measure text
    bbox = draw.textbbox((0, 0), text, font=font)
    text_w = bbox[2] - bbox[0]
    text_h = bbox[3] - bbox[1]
    w, h = img.size

    x, y = _resolve_position(position, w, h, text_w, text_h, padding)
    alpha = int(255 * opacity)

    # Shadow (50% of main opacity) for readability on any background
    draw.text((x + 1, y + 1), text, font=font, fill=(0, 0, 0, alpha // 2))
    # Main text (white)
    draw.text((x, y), text, font=font, fill=(255, 255, 255, alpha))

    return Image.alpha_composite(img, overlay).convert('RGB')


def _resolve_position(position, w, h, text_w, text_h, padding):
    mapping = {
        'top-left':     (padding, padding),
        'top-right':    (w - text_w - padding, padding),
        'bottom-left':  (padding, h - text_h - padding),
        'bottom-right': (w - text_w - padding, h - text_h - padding),
        'center':       ((w - text_w) // 2, (h - text_h) // 2),
    }
    return mapping[position]


def _load_font(size: int) -> ImageFont.FreeTypeFont:
    for path in _FONT_CANDIDATES:
        if os.path.exists(path):
            try:
                return ImageFont.truetype(path, size)
            except Exception:
                continue
    return ImageFont.load_default()
