#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
海报模板的抽象基类
"""

import logging
from abc import ABC, abstractmethod
from typing import Tuple, Dict, Any, Optional, List
from PIL import Image, ImageDraw

# 依赖本地的工具类
from ..utils import ImageProcessor, TextRenderer

logger = logging.getLogger(__name__)


class BaseTemplate(ABC):
    """
    所有海报模板的抽象基类。
    定义了模板的通用接口和基础功能。
    """
    
    def __init__(self, size: Tuple[int, int] = (900, 1200), font_dir: str = "/root/autodl-tmp/TCC_RESTRUCT/assets/font"):
        self.width, self.height = size
        self.size = size
        self.image_processor = ImageProcessor()
        self.text_renderer = TextRenderer(font_dir=font_dir)
        self.logger = logging.getLogger(self.__class__.__name__)

    @abstractmethod
    def generate(self, **kwargs) -> Image.Image:
        """
        生成海报的核心方法。
        每个子类必须实现此方法。
        kwargs: 包含生成海报所需的所有动态参数，如图片路径、文案内容等。
        """
        pass

    def create_canvas(self, background_color: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
        """创建一个指定尺寸和颜色的空白画布"""
        color = background_color or (255, 255, 255, 255)
        return Image.new("RGBA", self.size, color)

    def create_gradient_background(self, 
                                 top_color: Tuple[int, int, int],
                                 bottom_color: Tuple[int, int, int],
                                 direction: str = "vertical") -> Image.Image:
        """创建渐变背景图"""
        canvas = Image.new("RGBA", self.size)
        draw = ImageDraw.Draw(canvas)
        
        r1, g1, b1 = top_color
        r2, g2, b2 = bottom_color
        
        if direction == "vertical":
            for i in range(self.height):
                ratio = i / self.height
                r = int(r1 * (1 - ratio) + r2 * ratio)
                g = int(g1 * (1 - ratio) + g2 * ratio)
                b = int(b1 * (1 - ratio) + b2 * ratio)
                draw.line([(0, i), (self.width, i)], fill=(r, g, b, 255))
        else: # horizontal
            for i in range(self.width):
                ratio = i / self.width
                r = int(r1 * (1 - ratio) + r2 * ratio)
                g = int(g1 * (1 - ratio) + g2 * ratio)
                b = int(b1 * (1 - ratio) + b2 * ratio)
                draw.line([(i, 0), (i, self.height)], fill=(r, g, b, 255))
                
        return canvas

    def _validate_inputs(self, required_keys: List[str], **kwargs) -> bool:
        """一个简单的输入验证辅助方法"""
        for key in required_keys:
            if key not in kwargs or kwargs[key] is None:
                self.logger.error(f"生成海报失败: 缺少必需的参数 '{key}'")
                return False
        return True 