import os
import json
import jdatetime
from PIL import Image, ImageDraw, ImageFont

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ASSETS_DIR = os.path.join(BASE_DIR, 'assets')
OUTPUT_DIR = os.path.join(BASE_DIR, 'outputs')
FONTS_DIR = os.path.join(ASSETS_DIR, 'fonts')
CONFIG_DIR = os.path.join(BASE_DIR, 'config')

FONT_BOLD = os.path.join(FONTS_DIR, 'Vazirmatn-Bold.ttf')
FONT_REGULAR = os.path.join(FONTS_DIR, 'Vazirmatn-Regular.ttf')
TEMPLATE_CONFIG_PATH = os.path.join(CONFIG_DIR, 'template.json')

def to_persian_numbers(text):
    """تبدیل تمام ارقام انگلیسی به فارسی"""
    fa_digits = '۰۱۲۳۴۵۶۷۸۹'
    en_digits = '0123456789'
    for en, fa in zip(en_digits, fa_digits):
        text = text.replace(en, fa)
    return text

def wrap_text_native(text, font, max_width, draw):
    words = text.split()
    lines = []
    current_line = []
    for word in words:
        current_line.append(word)
        line_str = " ".join(current_line)
        length = draw.textlength(line_str, font=font, direction="rtl")
        if length > max_width and len(current_line) > 1:
            current_line.pop()
            lines.append(" ".join(current_line))
            current_line = [word]
    if current_line:
        lines.append(" ".join(current_line))
    return lines

def round_corners(image, radius):
    mask = Image.new('L', image.size, 0)
    draw = ImageDraw.Draw(mask)
    draw.rounded_rectangle([(0, 0), image.size], radius, fill=255)
    result = image.copy()
    result.putalpha(mask)
    return result

def clean_template_placeholders(template):
    # محو کامل کلمه تاریخ با بافت تمیز شیشه مجاور (محو کردن کامل تا نقطه شروع آیکون تقویم)
    patch_date = template.crop((250, 1540, 480, 1610))
    template.paste(patch_date, (480, 1540))
    template.paste(patch_date, (520, 1540))

def create_story(news_image_path, title, summary, output_filename="story.png"):
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    template = Image.open(os.path.join(ASSETS_DIR, 'template.png')).convert('RGBA')
    W, H = template.size
    
    clean_template_placeholders(template)
    
    # کادر دقیق عکس (مطابق نمونه اصلی)
    card_box = (248, 460, 832, 1044)
    if news_image_path and os.path.exists(news_image_path):
        card_w = card_box[2] - card_box[0]
        card_h = card_box[3] - card_box[1]
        with Image.open(news_image_path).convert('RGBA') as raw_img:
            min_dim = min(raw_img.size)
            left = (raw_img.width - min_dim) // 2
            top = (raw_img.height - min_dim) // 2
            cropped = raw_img.crop((left, top, left + min_dim, top + min_dim))
            resized = cropped.resize((card_w, card_h), Image.Resampling.LANCZOS)
            rounded_img = round_corners(resized, 75)
            template.paste(rounded_img, (card_box[0], card_box[1]), rounded_img)
            
    draw = ImageDraw.Draw(template)
    
    # فونت‌ها با تنظیم دقیق متناسب با تصویر هدف
    title_font = ImageFont.truetype(FONT_BOLD, 42, layout_engine=ImageFont.Layout.RAQM)
    summary_font = ImageFont.truetype(FONT_REGULAR, 31, layout_engine=ImageFont.Layout.RAQM)
    date_font = ImageFont.truetype(FONT_BOLD, 26, layout_engine=ImageFont.Layout.RAQM)
    
    # تیتر (رنگ زرد گرم و درخشان دقیقاً مشابه نمونه)
    title_lines = wrap_text_native(title, title_font, max_width=720, draw=draw)
    title_y = 1125
    for line in title_lines:
        draw.text((W // 2, title_y), line, font=title_font, fill="#FFB703", anchor="mm", direction="rtl", language="fa")
        title_y += 66

    # خلاصه خبر
    summary_lines = wrap_text_native(summary, summary_font, max_width=740, draw=draw)
    summary_y = max(title_y + 35, 1290)
    for line in summary_lines:
        draw.text((W // 2, summary_y), line, font=summary_font, fill="#F8FAFC", anchor="mm", direction="rtl", language="fa")
        summary_y += 54

    # تاریخ شمسی با اعداد فارسی
    weekdays = ["شنبه", "یکشنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنج‌شنبه", "جمعه"]
    now = jdatetime.datetime.now()
    shamsi_weekday = weekdays[now.weekday()]
    months = ["فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"]
    shamsi_date = f"{shamsi_weekday} {now.day} {months[now.month - 1]} {now.year}"
    shamsi_date_fa = to_persian_numbers(shamsi_date)
    
    # درج تاریخ در محل دقیق
    draw.text((610, 1572), shamsi_date_fa, font=date_font, fill="#FFFFFF", anchor="ra", direction="rtl", language="fa")

    output_path = os.path.join(OUTPUT_DIR, output_filename)
    template.save(output_path, "PNG", quality=95)
    print(f"SUCCESS: تصویر بازسازی شد -> {output_path}")
    return output_path

if __name__ == "__main__":
    # استخراج لوگوی اصلی ChatGPT از همان فایل هدف شما
    test_thumb = os.path.join(ASSETS_DIR, 'test_thumb.png')
    sample_file = os.path.join(ASSETS_DIR, 'sample_output.jpg')
    if os.path.exists(sample_file):
        with Image.open(sample_file) as sample:
            thumb = sample.crop((248, 460, 832, 1044))
            thumb.save(test_thumb)
            
    sample_title = "هوش مصنوعی GPT-6.1 Astra به‌دلیل «سوءرفتار» به تأخیر افتاد"
    sample_summary = "عرضه GPT-6.1 Astra به‌دلیل فریبکاری، سرپیچی از دستورها و تعامل بدون اجازه با سرویس‌های خارجی متوقف شد."
    create_story(test_thumb, sample_title, sample_summary, "target_match.png")
