#!/usr/bin/env python3
"""
GRILL PRICE OVERLAY TEMPLATE - NAJLEPSZA WERSJA
- Tytuł: DUŻY (auto-dopasowany, 20% marginesu)
- Pasek: 160px
- Kolor: Zielony (#1E7832), biały tekst
"""

import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw, ImageFont
import requests
from io import BytesIO
import os

# STYLE
BG_COLOR = "#1E7832"
TEXT_COLOR = "white"
BAR_HEIGHT = 160
MARGIN_PERCENT = 0.20  # 20% marginesu po bokach

FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"

def get_font(size):
    try:
        return ImageFont.truetype(FONT_PATH, size)
    except:
        return ImageFont.load_default()

def shorten_title(title, max_chars=32):
    """Skróć tytuł do max_chars znaków"""
    if len(title) <= max_chars:
        return title
    words = title.split()
    result = []
    total = 0
    for word in words:
        if total + len(word) + 1 <= max_chars:
            result.append(word)
            total += len(word) + 1
        else:
            break
    return ' '.join(result) + '...' if result else title[:max_chars-3] + '...'

def process_image(image_url, title, price, sale_price, output_path):
    """Dodaj pasek z tytułem i ceną do obrazu"""
    
    # Pobierz obraz
    resp = requests.get(image_url, timeout=15)
    img = Image.open(BytesIO(resp.content))
    
    if img.mode != 'RGB':
        img = img.convert('RGB')
    
    w, h = img.size
    
    # Oblicz maksymalną szerokość tekstu (80% - 20% marginesu)
    max_text_width = int(w * (1 - 2 * MARGIN_PERCENT))
    
    # Utwórz nowy obraz z paskiem
    new_img = Image.new('RGB', (w, h + BAR_HEIGHT), BG_COLOR)
    new_img.paste(img, (0, 0))
    
    draw = ImageDraw.Draw(new_img)
    
    # TYTUŁ - auto-dopasuj rozmiar
    short_title = shorten_title(title)
    
    # Znajdź największy font który się mieści
    font_size = 80  # Startuj od dużego
    title_font = get_font(font_size)
    
    while font_size > 28:
        bbox = draw.textbbox((0, 0), short_title, font=title_font)
        text_width = bbox[2] - bbox[0]
        if text_width <= max_text_width:
            break
        font_size -= 4
        title_font = get_font(font_size)
    
    # Wycentruj tytuł
    bbox = draw.textbbox((0, 0), short_title, font=title_font)
    text_width = bbox[2] - bbox[0]
    x = (w - text_width) // 2
    y = h + 20
    
    draw.text((x, y), short_title, font=title_font, fill=TEXT_COLOR)
    
    # CENA
    price_text = f"{sale_price}"
    if sale_price != price:
        price_text = f"{sale_price}  (było: {price})"
    
    price_font = get_font(32)
    bbox = draw.textbbox((0, 0), price_text, font=price_font)
    text_width = bbox[2] - bbox[0]
    x = (w - text_width) // 2
    y = h + 100
    
    draw.text((x, y), price_text, font=price_font, fill=TEXT_COLOR)
    
    # Zapisz
    new_img.save(output_path, 'JPEG', quality=90)
    return True

if __name__ == "__main__":
    # Przykład użycia
    process_image(
        image_url="https://example.com/image.jpg",
        title="GRILL GAZOWY Ogrodowy",
        price="816 PLN",
        sale_price="547 PLN",
        output_path="output.jpg"
    )
