#!/usr/bin/env python3
"""
Add watermark to all stock images
"""

from PIL import Image, ImageDraw, ImageFont
import os
from pathlib import Path

def add_watermark(image_path, watermark_text="cleankitchens.org"):
    """Add a subtle watermark to an image"""
    try:
        # Open the image
        img = Image.open(image_path)
        
        # Create a drawing context
        draw = ImageDraw.Draw(img)
        
        # Try to use a nice font, fallback to default if not available
        try:
            font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 14)
        except:
            font = ImageFont.load_default()
        
        # Get image dimensions
        width, height = img.size
        
        # Calculate text position (bottom right corner)
        text_bbox = draw.textbbox((0, 0), watermark_text, font=font)
        text_width = text_bbox[2] - text_bbox[0]
        text_height = text_bbox[3] - text_bbox[1]
        
        x = width - text_width - 10
        y = height - text_height - 10
        
        # Add semi-transparent white background for text
        padding = 5
        draw.rectangle(
            [(x - padding, y - padding), 
             (x + text_width + padding, y + text_height + padding)],
            fill=(255, 255, 255, 200)
        )
        
        # Add the text
        draw.text((x, y), watermark_text, fill=(100, 100, 100), font=font)
        
        # Save the image
        img.save(image_path, 'JPEG', quality=95)
        return True
        
    except Exception as e:
        print(f"Error adding watermark to {image_path}: {e}")
        return False

def main():
    base_dir = Path("/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images")
    
    # Process violations images
    violations_dir = base_dir / "violations"
    if violations_dir.exists():
        for img_file in violations_dir.glob("*.jpg"):
            if "optimized" not in str(img_file):
                print(f"Adding watermark to {img_file.name}")
                add_watermark(img_file)
    
    # Process chains images
    chains_dir = base_dir / "chains"
    if chains_dir.exists():
        for img_file in chains_dir.glob("*.jpg"):
            if "optimized" not in str(img_file):
                print(f"Adding watermark to {img_file.name}")
                add_watermark(img_file)
    
    print("Watermarks added successfully!")

if __name__ == "__main__":
    main()