from openai import OpenAI
import markdown
from bs4 import BeautifulSoup
import re
import json


def process_markdown_content(raw_content):
    """智能处理各种可能的Markdown格式输入，包括图表语法"""
    # 处理图表代码块（支持mermaid、vega-lite等）
    chart_patterns = [
        r'```mermaid(.*?)```',
        r'```vega-lite(.*?)```',
        r'```chart(.*?)```'
    ]

    # 保留原始图表代码块
    for pattern in chart_patterns:
        raw_content = re.sub(pattern, lambda m: f'<pre class="chart-block">{m.group(0)}</pre>', raw_content,
                             flags=re.DOTALL)

    # 处理普通代码块
    code_block_patterns = [
        r'```markdown(.*?)```',
        r'```(.*?)```',
        r'~~~(.*?)~~~'
    ]

    for pattern in code_block_patterns:
        matches = re.findall(pattern, raw_content, re.DOTALL)
        if matches:
            return matches[0].strip()

    return raw_content.strip()


def enhance_html_structure(soup):
    """增强HTML结构，特别处理图表"""
    # 图表块特殊处理
    for pre in soup.find_all('pre', class_='chart-block'):
        chart_type = 'mermaid' if 'mermaid' in pre.get_text() else 'vega-lite' if 'vega-lite' in pre.get_text() else 'chart'
        pre['class'] = f'chart-container {chart_type}-container'
        pre['data-chart-type'] = chart_type

        # 添加图表渲染占位符
        div = soup.new_tag('div', **{
            'class': 'rendered-chart',
            'data-chart-spec': pre.get_text()
        })
        pre.insert_after(div)

    # 表格增强
    for table in soup.find_all('table'):
        table['class'] = 'data-table'
        if not table.find('thead'):
            first_row = table.find('tr')
            if first_row:
                first_row.name = 'thead'
                for cell in first_row.find_all('td'):
                    cell.name = 'th'

    # 代码块增强
    for pre in soup.find_all('pre'):
        if not any(
                cls in pre.get('class', []) for cls in ['chart-container', 'mermaid-container', 'vega-lite-container']):
            if not pre.find('code'):
                code = soup.new_tag('code')
                code.string = pre.get_text()
                pre.clear()
                pre.append(code)
            pre['class'] = 'code-block'

    return soup


def generate_analysis_report(markdown_file):
    """生成自适应分析报告的主函数"""
    # 1. 读取Markdown文件
    with open(markdown_file, 'r', encoding='utf-8') as file:
        input_content = file.read()

    # 2. 调用API
    client = OpenAI(
        base_url='https://qianfan.baidubce.com/v2',
        api_key='bce-v3/ALTAK-X8C1AorvpdAI3ILPiRerh/4022de183e6b0a38e6b3baeb8af19e937f4a73d4'
    )

    response = client.chat.completions.create(
        model="ernie-x1-turbo-32k",
        messages=[{
            "role": "user",
            "content": f"{input_content}\n\n请生成专业的数据分析报告，要求：\n"
                       "1. 使用规范的Markdown格式\n"
                       "2. 包含业务表现分析、产品结构洞察、优化实施方案\n"
                        "3. 增加门店维度的数据分析"
                        "4.每个分析下需要展示对应的明细数据"
        }]
    )

    # 3. 处理API返回内容
    raw_content = response.choices[0].message.content
    processed_md = process_markdown_content(raw_content)

    # 4. 转换为HTML并增强结构
    html_content = markdown.markdown(processed_md, extensions=['tables', 'fenced_code', 'codehilite'])
    soup = BeautifulSoup(html_content, 'html.parser')
    enhanced_soup = enhance_html_structure(soup)

    # 5. 生成完整HTML报告（包含图表渲染支持）
    html_template = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI数据分析报告（含图表）</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <!-- 图表库 -->
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
    <style>
        :root {{
            --primary: #3498db;
            --secondary: #2ecc71;
            --accent: #e74c3c;
            --dark: #2c3e50;
            --light: #f8f9fa;
        }}

        body {{
            font-family: 'Noto Sans SC', sans-serif;
            line-height: 1.8;
            color: #333;
            background-color: var(--light);
        }}

        .report-container {{
            max-width: 1200px;
            margin: 40px auto;
            padding: 40px;
            background: white;
            box-shadow: 0 0 30px rgba(0,0,0,0.1);
            border-radius: 10px;
        }}

        /* 图表容器样式 */
        .chart-container {{
            margin: 30px 0;
            position: relative;
        }}

        .rendered-chart {{
            width: 100%;
            min-height: 300px;
            margin: 20px 0;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 15px;
            background: white;
        }}

        .mermaid-container, .vega-lite-container {{
            display: none; /* 隐藏原始代码块 */
        }}

        /* 响应式表格 */
        .data-table {{
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
        }}

        .data-table th {{
            background-color: var(--primary);
            color: white;
            padding: 12px 15px;
        }}

        .data-table td {{
            padding: 10px 15px;
            border-bottom: 1px solid #eee;
        }}

        @media (max-width: 768px) {{
            .report-container {{
                padding: 20px;
            }}
        }}
    </style>
</head>
<body>
    <div class="report-container">
        {enhanced_soup}
    </div>

    <script>
        // 渲染Mermaid图表
        mermaid.initialize({{ startOnLoad: true, theme: 'default' }});

        // 渲染Vega-Lite图表
        document.querySelectorAll('.rendered-chart').forEach(chartDiv => {{
            const spec = chartDiv.getAttribute('data-chart-spec');
            if (spec.includes('mermaid')) {{
                // Mermaid图表会自动渲染
                chartDiv.innerHTML = spec;
            }} else if (spec.includes('vega-lite') || spec.includes('"mark":')) {{
                // 解析Vega-Lite规范
                try {{
                    const chartSpec = JSON.parse(spec.replace(/^```vega-lite|```$/g, '').trim());
                    vegaEmbed(chartDiv, chartSpec, {{ actions: false }});
                }} catch (e) {{
                    console.error('图表解析错误:', e);
                    chartDiv.innerHTML = '<p>图表渲染失败: ' + e.message + '</p><pre>' + spec + '</pre>';
                }}
            }}
        }});
    </script>
</body>
</html>"""

    # 6. 保存报告
    output_file = 'chart_analysis_report.html'
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_template)

    return output_file


# 使用示例
if __name__ == "__main__":
    report_file = generate_analysis_report('analysis_report.md')
    print(f"带图表的分析报告已生成: {report_file}")