from PIL import Image, ImageDraw, ImageFont
import uuid
import os

def wrap_text(text, font, max_width, draw_dummy):
    """Helper function to wrap text natively using Raqm engine."""
    paragraphs = text.split('\n')
    all_lines = []
    
    for paragraph in paragraphs:
        if not paragraph.strip():
            all_lines.append("") 
            continue
            
        words = paragraph.split()
        current_line = []
        
        for word in words:
            current_line.append(word)
            test_line = ' '.join(current_line)
            
            # Natively calculate width of RTL text
            text_width = draw_dummy.textlength(test_line, font=font, direction='rtl', language='fa')
            
            if text_width > max_width:
                current_line.pop()
                all_lines.append(' '.join(current_line))
                current_line = [word]
        if current_line:
            all_lines.append(' '.join(current_line))
            
    return all_lines

def create_text_album(text, font_path="Vazirmatn-Bold.ttf"):
    """Generates 1080x1080 Square images for the Feed."""
    IMG_W, IMG_H = 1080, 1080
    MARGIN = 80
    BG_COLOR = (20, 20, 20)
    TEXT_COLOR = (245, 245, 245)
    MAX_LINES_PER_SLIDE = 9 

    try:
        font = ImageFont.truetype(font_path, 55)
    except IOError:
        print("❌ Font not found! Please ensure Vazirmatn-Bold.ttf is in the folder.")
        return []

    dummy_img = Image.new('RGB', (1, 1))
    draw_dummy = ImageDraw.Draw(dummy_img)
    max_text_width = IMG_W - (MARGIN * 2)

    all_lines = wrap_text(text, font, max_text_width, draw_dummy)
    slides_data = [all_lines[i:i + MAX_LINES_PER_SLIDE] for i in range(0, len(all_lines), MAX_LINES_PER_SLIDE)]
    
    if len(slides_data) > 10:
        slides_data = slides_data[:10]

    generated_files = []
    line_height = 95 
    
    for slide_lines in slides_data:
        img = Image.new('RGB', (IMG_W, IMG_H), color=BG_COLOR)
        draw = ImageDraw.Draw(img)
        
        total_text_height = len(slide_lines) * line_height
        y_text = (IMG_H - total_text_height) / 2
        
        for line in slide_lines:
            if line.strip():
                # Native Raqm width calculation
                text_width = draw.textlength(line, font=font, direction='rtl', language='fa')
                x_text = IMG_W - MARGIN - text_width 
                
                # THE FIX: Tell Pillow to use its native RTL engine
                draw.text((x_text, y_text), line, font=font, fill=TEXT_COLOR, direction='rtl', language='fa')
            
            y_text += line_height
            
        filename = f"text_slide_{uuid.uuid4().hex[:6]}.jpg"
        img.save(filename, quality=95)
        generated_files.append(filename)
        
    print(f"   🖼️ Generated {len(generated_files)} Feed images.")
    return generated_files

def create_native_story(text, font_path="Vazirmatn-Bold.ttf"):
    """Generates a native 1080x1920 Vertical image for Stories."""
    IMG_W, IMG_H = 1080, 1920
    MARGIN_X = 100
    MARGIN_Y = 350 
    BG_COLOR = (15, 15, 15)
    TEXT_COLOR = (245, 245, 245)

    try:
        font = ImageFont.truetype(font_path, 55)
    except IOError:
        return None

    dummy_img = Image.new('RGB', (1, 1))
    draw_dummy = ImageDraw.Draw(dummy_img)
    max_text_width = IMG_W - (MARGIN_X * 2)

    all_lines = wrap_text(text, font, max_text_width, draw_dummy)

    line_height = 95
    max_story_lines = (IMG_H - (MARGIN_Y * 2)) // line_height
    
    story_lines = all_lines[:max_story_lines]
    if len(all_lines) > max_story_lines:
        story_lines.append("...")

    img = Image.new('RGB', (IMG_W, IMG_H), color=BG_COLOR)
    draw = ImageDraw.Draw(img)
    
    total_text_height = len(story_lines) * line_height
    y_text = (IMG_H - total_text_height) / 2
    
    for line in story_lines:
        if line.strip():
            text_width = draw.textlength(line, font=font, direction='rtl', language='fa')
            x_text = IMG_W - MARGIN_X - text_width 
            
            # THE FIX: Tell Pillow to use its native RTL engine
            draw.text((x_text, y_text), line, font=font, fill=TEXT_COLOR, direction='rtl', language='fa')
        
        y_text += line_height
        
    story_filename = f"native_story_{uuid.uuid4().hex[:6]}.jpg"
    img.save(story_filename, quality=95)
    print("   📸 Generated Native 9:16 Story Image.")
    
    return story_filename