from zlapi.models import Message, ZaloAPIException, MultiMsgStyle, MessageStyle
import time
import os
import glob
import importlib
import emoji
import json
from PIL import Image, ImageDraw, ImageOps, ImageFont
import random
import logging
import emoji

# Cấu hình logging
logging.basicConfig(
    filename='menu.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

des = {
    'version': "1.0.3",
    'credits': "Vũ Xuân Kiên",
    'description': "Lệnh menu",
    'power': "Thành viên"
}

def get_commands_from_modules():
    module_dir = "modules"
    command_files = glob.glob(os.path.join(module_dir, "*.py"))
    commands = [os.path.splitext(os.path.basename(f))[0] for f in command_files if os.path.isfile(f) and f != '__init__.py']
    return commands

def get_all_vxkiue_with_info():
    vxkiue_info = {}
    for module_name in os.listdir('modules'):
        if module_name.endswith('.py') and module_name != '__init__.py' and module_name != 'menu.py':
            module_path = f'modules.{module_name[:-3]}'
            try:
                module = importlib.import_module(module_path)
                if hasattr(module, 'des'):
                    des = getattr(module, 'des')
                    version = des.get('version', 'Chưa có thông tin')
                    credits = des.get('credits', 'Chưa có thông tin')
                    description = des.get('description', 'Chưa có thông tin')
                    power = des.get('power', 'Chưa có thông tin')
                    vxkiue_info[module_name[:-3]] = (version, credits, description, power)
            except Exception as e:
                logger.error(f"Error loading module {module_name}: {e}")
                continue
    return vxkiue_info

def load_alias_commands():
    try:
        with open("modules/cache/alias_commands.json", "r", encoding="utf-8") as f:
            data = json.load(f)
            return data.get("aliases", {})
    except (FileNotFoundError, json.JSONDecodeError):
        return {}

def get_random_background():
    """Lấy ngẫu nhiên một ảnh background từ thư mục background."""
    background_dir = "background"
    if not os.path.exists(background_dir):
        os.makedirs(background_dir)
        logger.warning(f"Thư mục background không tồn tại, đã tạo mới tại {background_dir}")
        return None
    background_files = glob.glob(os.path.join(background_dir, "*.jpg")) + \
                      glob.glob(os.path.join(background_dir, "*.png"))
    return random.choice(background_files) if background_files else None

def create_menu_image(vxkiue_info, alias_commands, current_page, total_pages, total_commands):
    """Tạo ảnh menu với background mờ và gradient text."""
    scale = 2
    font_path = "modules/cache/font/arial unicode ms.otf"
    emoji_font_path = "modules/cache/font/emoji.ttf"
    if not os.path.exists(font_path) or not os.path.exists(emoji_font_path):
        logger.error(f"Font files not found: {font_path} or {emoji_font_path}")
        return None

    font = ImageFont.truetype(font_path, 32 * scale)
    emoji_font = ImageFont.truetype(emoji_font_path, 32 * scale)
    padding = 80 * scale
    img_width = 1200 * scale
    img_height = 800 * scale  # Tăng chiều cao để chứa 8 lệnh và hướng dẫn

    # Lấy background ngẫu nhiên
    background_path = get_random_background()
    if not background_path:
        background = Image.new("RGB", (img_width, img_height), (25, 25, 25))
    else:
        try:
            background = Image.open(background_path).convert("RGB")
            background = ImageOps.fit(background, (img_width, img_height), centering=(0.5, 0.5))
        except Exception as e:
            logger.error(f"Error loading background {background_path}: {e}")
            background = Image.new("RGB", (img_width, img_height), (25, 25, 25))

    # Tạo overlay mờ
    overlay = Image.new("RGBA", (img_width, img_height), (0, 0, 0, 128))
    background.paste(overlay, (0, 0), overlay)

    draw = ImageDraw.Draw(background)

    # Gradient colors (giống scl)
    base_colors = [(102, 204, 255), (255, 255, 180), (102, 255, 204)]
    colors = random.sample(base_colors, 3)

    def get_gradient_color(x, total_width):
        ratio = x / total_width
        if ratio < 0.5:
            c1, c2 = colors[0], colors[1]
            ratio *= 2
        else:
            c1, c2 = colors[1], colors[2]
            ratio = (ratio - 0.5) * 2
        r = int(c1[0] + (c2[0] - c1[0]) * ratio)
        g = int(c1[1] + (c2[1] - c1[1]) * ratio)
        b = int(c1[2] + (c2[2] - c1[2]) * ratio)
        return (r, g, b)

    def draw_gradient_text_line(draw, text, x, y, font, emoji_font):
        total_width = sum((emoji_font if emoji.emoji_count(char) > 0 else font).getlength(char) for char in text)
        current_x = x
        for char in text:
            f = emoji_font if emoji.emoji_count(char) > 0 else font
            char_width = f.getlength(char)
            color = get_gradient_color(current_x - x, total_width)
            draw.text((current_x, y), char, font=f, fill=color)
            current_x += char_width
        return y + int(font.size * 1.6)

    # Vẽ tiêu đề
    title = f"🚦 Menu Commands (Page {current_page}/{total_pages})"
    text_y = padding
    text_y = draw_gradient_text_line(draw, title, padding, text_y, font, emoji_font)

    # Vẽ danh sách 8 lệnh
    items_per_page = 8
    start_index = (current_page - 1) * items_per_page
    end_index = start_index + items_per_page
    for i, (command_name, (_, _, description, power)) in enumerate(list(vxkiue_info.items())[start_index:end_index], start_index + 1):
        text = f"{i}. {command_name} - {description} - {power}"
        text_y = draw_gradient_text_line(draw, text, padding, text_y, font, emoji_font)

    # Vẽ hướng dẫn sử dụng dưới cùng
    footer_text = ""
    if current_page == 1 and total_pages > 1:
        footer_text = "-----------------\nVui lòng .menu 2 để xem thêm lệnh\n-----------------"
    elif current_page < total_pages:
        footer_text = f"-----------------\n.menu {current_page + 1}\n-----------------"
    else:
        footer_text = f"-----------------\nCảm ơn đã xem hết chúng tui có {total_commands} lệnh\n-----------------"
    text_y = draw_gradient_text_line(draw, footer_text, padding, text_y + padding // 2, font, emoji_font)

    # Lưu ảnh
    cache_dir = os.path.join(os.path.dirname(__file__), "cache")
    os.makedirs(cache_dir, exist_ok=True)
    image_path = os.path.join(cache_dir, f"menu_image_page_{current_page}.png")
    background.save(image_path, format="PNG", quality=95)
    return image_path

def handle_menu_command(message, message_object, thread_id, thread_type, author_id, client):
    vxkiue_info = get_all_vxkiue_with_info()
    alias_commands = load_alias_commands()
    items_per_page = 8
    args = message.split()
    current_page = 1
    if len(args) > 1:
        try:
            current_page = int(args[1])
        except ValueError:
            current_page = 1
    
    total_commands = len(vxkiue_info)
    total_pages = (total_commands + items_per_page - 1) // items_per_page
    current_page = max(1, min(current_page, total_pages))

    if not vxkiue_info:
        menu_text = "Không có lệnh nào trong modules."
        client.replyMessage(Message(text=menu_text), message_object, thread_id, thread_type, ttl=60000)
        return

    # Tạo và gửi ảnh
    image_path = create_menu_image(vxkiue_info, alias_commands, current_page, total_pages, total_commands)
    if image_path and os.path.exists(image_path):
        try:
            with Image.open(image_path) as img:
                width, height = img.size
            client.sendLocalImage(
                imagePath=image_path,
                thread_id=thread_id,
                thread_type=thread_type,
                width=width,
                height=height,
                ttl=60000
            )
            logger.info(f"Sent menu image for page {current_page}/{total_pages}")
        except Exception as e:
            logger.error(f"Error sending menu image: {e}")
            menu_text = "❌ Lỗi khi tạo hoặc gửi ảnh menu."
            client.replyMessage(Message(text=menu_text), message_object, thread_id, thread_type, ttl=60000)
        finally:
            os.remove(image_path)
            logger.info(f"Deleted temporary menu image: {image_path}")
    else:
        logger.error("Failed to create menu image")
        menu_text = "❌ Không thể tạo ảnh menu. Kiểm tra thư mục background/ và font/."
        client.replyMessage(Message(text=menu_text), message_object, thread_id, thread_type, ttl=60000)

def ft_vxkiue():
    return {
        'menu': handle_menu_command
    }