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

"""
Business Template
商务风格海报模板 - 重构版本，适用于专业、高端场景
"""

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

from .base_template import BaseTemplate
from ....exceptions import PosterGenerationError

logger = logging.getLogger(__name__)


class BusinessTemplate(BaseTemplate):
    """
    商务风格模板 - 重构版本
    适用于酒店、房地产、高端服务等场景
    特点是上下图片融合，中间为信息展示区，整体风格沉稳、专业
    """
    
    SUPPORTED_FEATURES = [
        "dual_image_layout",
        "professional_colors",
        "clean_typography",
        "symmetrical_design"
    ]

    def __init__(self, size: Tuple[int, int] = (900, 1200), config: Optional[Dict[str, Any]] = None):
        super().__init__(size, config)
        
        # 商务模板特定配置
        self.layout_config = {
            'total_parts': 4.0,
            'transparent_ratio': 0.5,
            'content_margin': 20,
            'section_spacing': 35,
            'bottom_reserve': 40
        }
        
        logger.debug("BusinessTemplate 初始化完成")

    def generate(
        self,
        images: List[Image.Image],
        content: Optional[Dict[str, Any]] = None,
        color_theme: Optional[str] = None,
        **kwargs
    ) -> Image.Image:
        """
        生成Business风格海报

        Args:
            images: 图像列表（至少需要2张：顶部和底部）
            content: 文本内容字典
            color_theme: 预设颜色主题名称
            **kwargs: 其他参数

        Returns:
            生成的海报图像

        Raises:
            PosterGenerationError: 生成失败时抛出
        """
        try:
            # 验证输入
            if not self._validate_inputs(['images'], images=images):
                raise PosterGenerationError("输入验证失败")
            
            if not self._validate_images(images):
                raise PosterGenerationError("图像验证失败")
            
            if len(images) < 1:
                raise PosterGenerationError("Business模板至少需要1张图像")
            
            if content and not self._validate_content(content):
                raise PosterGenerationError("内容验证失败")
            
            # 使用默认内容（如果未提供）
            if content is None:
                content = self._get_default_content()

            # 处理图像
            top_img = images[0]
            bottom_img = images[1] if len(images) > 1 else images[0]
            
            # 调整图像尺寸
            top_img = self.image_processor.resize_and_crop(top_img, (self.width, self.height // 3))
            bottom_img = self.image_processor.resize_and_crop(bottom_img, (self.width, self.height // 3))
            
            # 获取颜色主题
            if color_theme:
                colors = self.get_color_theme(color_theme)
                top_color, bottom_color = colors[0], colors[1] if len(colors) > 1 else colors[0]
            else:
                # 从图像提取主色调
                top_color = self._extract_dominant_color(top_img)
                bottom_color = self._extract_dominant_color(bottom_img)
                top_color, bottom_color = self._ensure_colors_harmony(top_color, bottom_color)
            
            # 创建渐变背景
            canvas = self.create_gradient_background(top_color, bottom_color)
            
            # 应用图像透明度效果
            top_img_trans = self._apply_transparency(top_img, "top")
            bottom_img_trans = self._apply_transparency(bottom_img, "bottom")
            
            # 计算布局
            section_heights = self._calculate_section_heights()
            
            # 合成图像
            canvas = self._compose_images(canvas, top_img_trans, bottom_img_trans, section_heights)
            
            # 添加装饰元素
            canvas = self._add_decorative_elements(canvas)
            
            # 渲染文本
            canvas = self._render_business_texts(canvas, content, section_heights)
            
            return canvas

        except Exception as e:
            error_msg = f"BusinessTemplate生成失败: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise PosterGenerationError(error_msg)

    def _get_default_content(self) -> Dict[str, Any]:
        """获取默认内容"""
        return {
            "title": "专业服务",
            "content": "为您提供高品质的专业服务体验，值得信赖的选择。",
            "tags": ["专业", "品质", "服务"],
            "call_to_action": "了解更多"
        }

    def _extract_dominant_color(self, image: Image.Image) -> Tuple[int, int, int]:
        """提取图像主色调"""
        # 简化实现：从边缘区域提取颜色
        edge_pixels = []
        
        # 提取顶部边缘
        for x in range(0, image.width, 10):
            pixel = image.getpixel((x, 0))
            edge_pixels.append(pixel)
        
        # 提取底部边缘
        for x in range(0, image.width, 10):
            pixel = image.getpixel((x, image.height - 1))
            edge_pixels.append(pixel)
        
        if edge_pixels:
            # 计算平均颜色
            avg_r = sum(p[0] for p in edge_pixels) // len(edge_pixels)
            avg_g = sum(p[1] for p in edge_pixels) // len(edge_pixels)
            avg_b = sum(p[2] for p in edge_pixels) // len(edge_pixels)
            return (avg_r, avg_g, avg_b)
        
        return (70, 70, 70)  # 默认深灰色

    def _ensure_colors_harmony(
        self, 
        color1: Tuple[int, int, int], 
        color2: Tuple[int, int, int]
    ) -> Tuple[Tuple[int, int, int], Tuple[int, int, int]]:
        """确保颜色和谐"""
        # 简化和谐算法：调整饱和度和明度
        def adjust_color(color):
            r, g, b = color
            # 降低饱和度，增加专业感
            factor = 0.7
            gray = (r + g + b) // 3
            new_r = int(r * factor + gray * (1 - factor))
            new_g = int(g * factor + gray * (1 - factor))
            new_b = int(b * factor + gray * (1 - factor))
            return (new_r, new_g, new_b)
        
        return adjust_color(color1), adjust_color(color2)

    def _apply_transparency(self, image: Image.Image, position: str) -> Image.Image:
        """应用透明度效果"""
        result = image.convert("RGBA")
        
        # 创建透明度渐变遮罩
        mask = Image.new("L", image.size, 255)
        
        if position == "top":
            # 顶部图像：底部渐变透明
            for y in range(image.height):
                opacity = int(255 * (1 - (y / image.height) * 0.3))
                for x in range(image.width):
                    mask.putpixel((x, y), opacity)
        else:
            # 底部图像：顶部渐变透明
            for y in range(image.height):
                opacity = int(255 * (1 - ((image.height - y) / image.height) * 0.3))
                for x in range(image.width):
                    mask.putpixel((x, y), opacity)
        
        result.putalpha(mask)
        return result

    def _calculate_section_heights(self) -> Dict[str, int]:
        """计算各部分高度"""
        top_section = self.height // 4
        middle_section = self.height // 2
        bottom_section = self.height // 4
        
        return {
            "top": top_section,
            "middle": middle_section,
            "bottom": bottom_section,
            "middle_start": top_section,
            "bottom_start": top_section + middle_section
        }

    def _compose_images(
        self, 
        canvas: Image.Image, 
        top_img: Image.Image, 
        bottom_img: Image.Image,
        sections: Dict[str, int]
    ) -> Image.Image:
        """合成图像"""
        result = canvas.copy()
        
        # 贴上顶部图像
        result.paste(top_img, (0, 0), top_img if top_img.mode == "RGBA" else None)
        
        # 贴上底部图像
        bottom_y = sections["bottom_start"]
        result.paste(bottom_img, (0, bottom_y), bottom_img if bottom_img.mode == "RGBA" else None)
        
        return result

    def _add_decorative_elements(self, canvas: Image.Image) -> Image.Image:
        """添加装饰元素"""
        result = canvas.copy()
        draw = ImageDraw.Draw(result)
        
        # 添加分隔线
        line_y = self.height // 2
        line_color = (255, 255, 255, 100)
        draw.line([(50, line_y), (self.width - 50, line_y)], fill=line_color, width=2)
        
        return result

    def _render_business_texts(
        self, 
        canvas: Image.Image, 
        content: Dict[str, Any], 
        sections: Dict[str, int]
    ) -> Image.Image:
        """渲染商务风格文本"""
        result = canvas.copy()
        
        # 中间内容区域
        content_area_start = sections["middle_start"] + 30
        content_width = self.width - 100  # 左右各留50像素
        content_x = 50
        
        current_y = content_area_start
        
        # 渲染标题（居中，大字体）
        title = content.get("title", "")
        if title:
            title_size = 42
            title_width, _ = self.text_renderer.get_text_size(title, title_size)
            title_x = (self.width - title_width) // 2
            
            result = self.text_renderer.render_text_with_effects(
                image=result,
                text=title,
                position=(title_x, current_y),
                font_size=title_size,
                color=(255, 255, 255),
                effects={"shadow": True, "shadow_offset": [2, 2]}
            )
            current_y += title_size + 30
        
        # 渲染主要内容（居中对齐）
        main_content = content.get("content", "")
        if main_content:
            content_size = 20
            
            # 自动换行
            wrapped_lines = self.text_renderer.wrap_text(
                text=main_content,
                max_width=content_width,
                font_size=content_size
            )
            
            result = self.text_renderer.render_multiline_text(
                image=result,
                text_lines=wrapped_lines,
                start_position=(self.width // 2, current_y),
                font_size=content_size,
                line_spacing=10,
                color=(240, 240, 240),
                align="center"
            )
            
            current_y += len(wrapped_lines) * (content_size + 10) + 25
        
        # 渲染标签（居中）
        tags = content.get("tags", [])
        if tags:
            tags_text = " | ".join(tags)
            tags_width, _ = self.text_renderer.get_text_size(tags_text, 16)
            tags_x = (self.width - tags_width) // 2
            
            result = self.text_renderer.render_text(
                image=result,
                text=tags_text,
                position=(tags_x, current_y),
                font_size=16,
                color=(200, 200, 200)
            )
            current_y += 16 + 20
        
        # 渲染行动召唤（居中按钮）
        cta = content.get("call_to_action", "")
        if cta:
            cta_button_width = 180
            cta_button_height = 50
            cta_x = (self.width - cta_button_width) // 2
            cta_y = current_y
            
            # 绘制专业风格按钮
            draw = ImageDraw.Draw(result)
            button_color = (80, 80, 80)  # 深灰色，专业感
            draw.rounded_rectangle(
                [cta_x, cta_y, cta_x + cta_button_width, cta_y + cta_button_height],
                radius=5,  # 较小的圆角，更专业
                fill=button_color,
                outline=(255, 255, 255),
                width=2
            )
            
            # 渲染CTA文本（居中）
            cta_text_x = cta_x + cta_button_width // 2
            cta_text_y = cta_y + 15
            result = self.text_renderer.render_text(
                image=result,
                text=cta,
                position=(cta_text_x, cta_text_y),
                font_size=20,
                color=(255, 255, 255),
                anchor="mm"
            )
        
        return result 