"""
HTML模板工具模块

提供HTML文档生成功能，支持：
- HTML文档结构生成
- 表格生成（支持字典列表和对象列表）
- 样式化邮件模板
- 链接生成
"""
from typing import List, Dict, Any, Union, Optional


class HtmlTemplate:
    """
    HTML模板生成类

    提供静态方法生成HTML文档和组件，主要用于邮件和报表的HTML化。

    Example:
        >>> data = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
        >>> html = HtmlTemplate.get_html_table(data)
    """

    # HTML 结构：<html> <head></head> <body></body> </html>
    TEMPLATE_HTML = """ <html> {} {} </html> """

    # HEADER 结构：<head> <meta></meta> <script></script> </head>
    TEMPLATE_HEAD = """ <head><meta charset="utf-8"> {} </head> """

    # BODY
    TEMPLATE_BODY = """
        <body style="height:100%; width: 100%; margin-left:2%;">
        {}
        {}
        </body>
    """

    # CSS样式
    TEMPLATE_CSS = """
        <style>
            .mail-table {
                font-family: Arial, Helvetica, sans-serif;
                border-collapse: collapse;
                min-width: 600px;
            }

            .mail-table td, .mail-table th {
                border: 1px solid #ddd;
                padding: 8px;
            }

            .mail-table tr:nth-child(even){background-color: #f2f2f2;}

            .mail-table tr:hover {background-color: #ddd;}

            .mail-table th {
                padding-top: 6px;
                padding-bottom: 6px;
                text-align: center;
                background-color: #3f98b1;
                color: white;
            }
            ol {
                list-style: none;
                counter-reset: steps;
            }
            ol li {
                counter-increment: steps;
            }
            ol li::before {
                content: counter(steps);
                margin-right: 0.5rem;
                background: #ff6f00;
                color: white;
                width: 1.2em;
                height: 1.2em;
                border-radius: 50%;
                display: inline-grid;
                place-items: center;
                line-height: 1.2em;
            }
            ol ol li::before {
                background: darkorchid;
            }
        </style>
    """

    # TABLE
    TEMPLATE_TABLE = """
         <table class="mail-table">
         <tbody> {} </tbody>
         </table>
    """
    TEMPLATE_TABLE_TR = """ <tr> {} </tr> """
    TEMPLATE_TABLE_TH = """ <th> {} </th> """
    TEMPLATE_TABLE_TD = """ <td> {} </td> """
    TEMPLATE_TABLE_TD_LEFT = """ <td style="text-align:left;"> {} </td> """
    TEMPLATE_TABLE_TD_CENTER = """ <td style="text-align:center;"> {} </td> """

    @staticmethod
    def get_html(content: str) -> str:
        """
        生成完整的HTML文档

        Args:
            content: HTML内容

        Returns:
            完整的HTML文档字符串
        """
        body = HtmlTemplate.TEMPLATE_BODY.format(HtmlTemplate.TEMPLATE_CSS, content)
        html = HtmlTemplate.TEMPLATE_HTML.format("", body)
        return html

    @staticmethod
    def get_html_table(dict_list: List[Union[Dict[str, Any], Any]]) -> str:
        """
        将字典列表转换为HTML表格文档

        Args:
            dict_list: 字典列表或对象列表

        Returns:
            包含表格的完整HTML文档
        """
        content = HtmlTemplate.get_table(dict_list)
        body = HtmlTemplate.TEMPLATE_BODY.format(HtmlTemplate.TEMPLATE_CSS, content)
        html = HtmlTemplate.TEMPLATE_HTML.format("", body)
        return html

    @staticmethod
    def get_table(dict_list: List[Union[Dict[str, Any], Any]]) -> str:
        """
        将字典列表或对象列表转换为HTML表格

        Args:
            dict_list: 字典列表或对象列表

        Returns:
            HTML表格字符串，空列表返回空字符串
        """
        if not dict_list:
            return ""

        # 获取字段列表
        first = dict_list[0]
        if isinstance(first, dict):
            fields = tuple(first.keys())
        else:
            fields = tuple(first.__dict__.keys())

        # 构建表头
        head = ""
        for field in fields:
            head += HtmlTemplate.TEMPLATE_TABLE_TH.format(field)
        head_line = HtmlTemplate.TEMPLATE_TABLE_TR.format(head)
        content = head_line

        # 构建数据行
        for data in dict_list:
            if not isinstance(data, dict):
                data = data.__dict__
            row = ""
            for field in fields:
                value = HtmlTemplate._get_value(data, field)
                row += HtmlTemplate.TEMPLATE_TABLE_TD_CENTER.format(value)
            content += HtmlTemplate.TEMPLATE_TABLE_TR.format(row)

        return HtmlTemplate.TEMPLATE_TABLE.format(content)

    @staticmethod
    def _get_value(data: Dict[str, Any], key: str) -> Any:
        """
        安全获取字典值

        Args:
            data: 数据字典
            key: 键名

        Returns:
            键对应的值，不存在时返回空字符串
        """
        if isinstance(data, dict) and key in data:
            return data[key]
        return ""

    @staticmethod
    def get_tag_a(url: str, desc: str, target: str = "_blank") -> str:
        """
        生成HTML链接标签

        Args:
            url: 链接地址
            desc: 链接文本
            target: 打开方式，默认新窗口打开

        Returns:
            HTML链接标签字符串
        """
        return f'<a href="{url}" target="{target}">{desc}</a>'
