#!/usr/bin/env python
# coding=utf-8
"""
Step10: 生成分析报告 HTML - 按分析步骤一步步展示
"""
import pandas as pd
import json
from pathlib import Path

output_dir = Path(__file__).parent / "output"

# 读取各步骤数据
df_daily = pd.read_csv(output_dir / "step7_头部vov趋势_合并.csv").sort_values('dt')
df_monthly = pd.read_csv(output_dir / "step7_月度统计.csv")

# 图表数据
dates = df_daily['dt'].astype(str).tolist()
vov_data = df_daily['vov_mean'].round(4).tolist()
problem_data = df_daily['problem_pct'].round(1).tolist()
str_data = [round(x*100, 2) for x in df_daily['str_mean'].tolist()]
vor_data = df_daily['vor_mean'].round(2).tolist()

# 月度数据
monthly_data = []
for _, row in df_monthly.iterrows():
    monthly_data.append({
        'month': str(row['month']),
        'vov': round(row['vov均值'], 4),
        'str': round(row['str'], 4),
        'ros': round(row['ros'], 2),
        'vor': round(row['vor'], 2),
        'problem': round(row['问题比例%'], 1)
    })

html_content = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>低VoV高曝光问题分析报告</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation"></script>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 40px 20px;
        }}
        .report {{
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }}
        .header {{
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }}
        .header h1 {{ font-size: 32px; margin-bottom: 10px; }}
        .header p {{ opacity: 0.8; }}

        .step {{
            padding: 40px;
            border-bottom: 1px solid #eee;
        }}
        .step:last-child {{ border-bottom: none; }}

        .step-header {{
            display: flex;
            align-items: center;
            margin-bottom: 24px;
        }}
        .step-number {{
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 18px;
            margin-right: 16px;
        }}
        .step-title {{
            font-size: 22px;
            color: #1a1a2e;
        }}
        .step-question {{
            color: #666;
            font-size: 14px;
        }}

        .answer-box {{
            background: #f8f9fa;
            border-left: 4px solid #27ae60;
            padding: 20px;
            margin: 20px 0;
            border-radius: 0 8px 8px 0;
        }}
        .answer-box.warning {{ border-left-color: #f39c12; }}
        .answer-box.danger {{ border-left-color: #e74c3c; }}

        .answer-title {{
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
        }}
        .answer-value {{
            font-size: 28px;
            font-weight: bold;
            color: #27ae60;
        }}
        .answer-box.warning .answer-value {{ color: #f39c12; }}
        .answer-box.danger .answer-value {{ color: #e74c3c; }}

        .metric-grid {{
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
            margin: 20px 0;
        }}
        .metric-card {{
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }}
        .metric-card.good {{ background: #d4edda; }}
        .metric-card.bad {{ background: #f8d7da; }}
        .metric-label {{ font-size: 14px; color: #666; margin-bottom: 8px; }}
        .metric-value {{ font-size: 24px; font-weight: bold; }}
        .metric-card.good .metric-value {{ color: #155724; }}
        .metric-card.bad .metric-value {{ color: #721c24; }}

        .chart-container {{
            height: 300px;
            margin: 20px 0;
        }}

        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }}
        th, td {{
            padding: 12px;
            text-align: center;
            border-bottom: 1px solid #eee;
        }}
        th {{ background: #f8f9fa; font-weight: 600; }}
        tr.problem {{ background: #fff5f5; }}
        .badge {{
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
        }}
        .badge-danger {{ background: #f8d7da; color: #721c24; }}
        .badge-warning {{ background: #fff3cd; color: #856404; }}
        .badge-success {{ background: #d4edda; color: #155724; }}

        .conclusion {{
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            color: white;
            padding: 40px;
        }}
        .conclusion h2 {{ margin-bottom: 20px; }}
        .conclusion ul {{ margin-left: 20px; }}
        .conclusion li {{ margin-bottom: 12px; line-height: 1.8; }}
        .highlight {{ background: rgba(255,255,255,0.2); padding: 2px 8px; border-radius: 4px; }}

        .timeline {{
            position: relative;
            padding-left: 30px;
        }}
        .timeline::before {{
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #ddd;
        }}
        .timeline-item {{
            position: relative;
            margin-bottom: 20px;
        }}
        .timeline-item::before {{
            content: '';
            position: absolute;
            left: -24px;
            top: 6px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #667eea;
        }}
        .timeline-item.bad::before {{ background: #e74c3c; }}
        .timeline-item.good::before {{ background: #27ae60; }}
    </style>
</head>
<body>
    <div class="report">
        <!-- 报告头部 -->
        <div class="header">
            <h1>📊 低VoV高曝光问题分析报告</h1>
            <p>数据范围: {dates[0]} ~ {dates[-1]} | 共 {len(dates)} 天</p>
        </div>

        <!-- Step 0: 问题背景 -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">0</div>
                <div>
                    <div class="step-title">问题背景</div>
                    <div class="step-question">什么是低VoV高曝光问题？</div>
                </div>
            </div>
            <p style="line-height:1.8;color:#555;">
                <strong>排序公式</strong>：score = STR × ROS × VOR = VoV<br><br>
                • <strong>STR</strong> (分享率): FM模型预估，用户看到视频后分享的概率<br>
                • <strong>ROS</strong> (回流/分享比): XGB模型预估，每次分享能带来多少回流用户<br>
                • <strong>VOR</strong> (病毒因子): 24h统计量，每个回流用户能带来多少曝光<br>
                • <strong>VoV</strong> (病毒系数): 最终的传播效率 = STR × ROS × VOR<br><br>
                <strong style="color:#e74c3c;">问题现象</strong>：某些视频真实VoV很低，但却获得了很高的曝光排名
            </p>
        </div>

        <!-- Step 1: 验证现象 -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">1</div>
                <div>
                    <div class="step-title">验证现象</div>
                    <div class="step-question">低VoV高曝光问题存在吗？</div>
                </div>
            </div>
            <div class="answer-box danger">
                <div class="answer-title">结论：问题确实存在 ✓</div>
                <div class="answer-value">43.5% 的 Top10 记录存在此问题</div>
            </div>
            <p style="color:#666;margin-top:12px;">
                定义：VoV < 0.35 但曝光排名 ≤ 5 的视频<br>
                验证方法：统计每日 Top10 曝光视频中符合条件的比例
            </p>
        </div>

        <!-- Step 2: 影响面 -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">2</div>
                <div>
                    <div class="step-title">量化影响</div>
                    <div class="step-question">问题影响有多大？</div>
                </div>
            </div>
            <div class="metric-grid">
                <div class="metric-card bad">
                    <div class="metric-label">问题记录占比</div>
                    <div class="metric-value">38.1%</div>
                </div>
                <div class="metric-card bad">
                    <div class="metric-label">问题视频数</div>
                    <div class="metric-value">21 个</div>
                </div>
                <div class="metric-card bad">
                    <div class="metric-label">影响曝光量</div>
                    <div class="metric-value">35.7%</div>
                </div>
            </div>
            <p style="color:#666;">
                即：超过1/3的头部曝光被低效率视频占据
            </p>
        </div>

        <!-- Step 3: 原因分析 -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">3</div>
                <div>
                    <div class="step-title">原因分析</div>
                    <div class="step-question">STR、ROS、VOR 哪个出了问题？</div>
                </div>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>指标</th>
                        <th>预估偏差</th>
                        <th>偏高比例</th>
                        <th>诊断</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>STR (分享率)</td>
                        <td>-5.7%</td>
                        <td>36.4%</td>
                        <td><span class="badge badge-success">正常</span></td>
                    </tr>
                    <tr class="problem">
                        <td><strong>ROS (回流比)</strong></td>
                        <td><strong>+72.2%</strong></td>
                        <td><strong>70.1%</strong></td>
                        <td><span class="badge badge-danger">系统性偏高 ⚠️</span></td>
                    </tr>
                    <tr>
                        <td>VOR (病毒因子)</td>
                        <td>混合</td>
                        <td>44.8%</td>
                        <td><span class="badge badge-warning">有异常值</span></td>
                    </tr>
                </tbody>
            </table>
            <div class="answer-box danger">
                <div class="answer-title">核心问题找到了！</div>
                <div class="answer-value">ROS 预估系统性偏高 72.2%</div>
            </div>
        </div>

        <!-- Step 4: 深入分析 ROS -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">4</div>
                <div>
                    <div class="step-title">ROS 偏差深入分析</div>
                    <div class="step-question">ROS 为什么会偏高？</div>
                </div>
            </div>
            <p style="margin-bottom:20px;color:#555;">发现 ROS 偏差与真实 ROS 呈强负相关 (r = -0.607)：</p>
            <table>
                <thead>
                    <tr>
                        <th>真实 ROS</th>
                        <th>预估偏差</th>
                        <th>说明</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="problem">
                        <td>< 2</td>
                        <td><strong>+152%</strong></td>
                        <td><span class="badge badge-danger">严重偏高</span></td>
                    </tr>
                    <tr>
                        <td>2-4</td>
                        <td>+20%</td>
                        <td>轻微偏高</td>
                    </tr>
                    <tr>
                        <td>4-6</td>
                        <td>-27%</td>
                        <td>偏低</td>
                    </tr>
                    <tr>
                        <td>> 6</td>
                        <td>-54%</td>
                        <td>严重偏低</td>
                    </tr>
                </tbody>
            </table>
            <div class="answer-box warning">
                <div class="answer-title">根本原因</div>
                <div class="answer-value">XGB 模型存在「回归均值」问题</div>
            </div>
            <p style="color:#666;margin-top:12px;">
                模型倾向于把极端值往中间拉：低的预估偏高，高的预估偏低
            </p>
        </div>

        <!-- Step 5: 时间趋势 -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">5</div>
                <div>
                    <div class="step-title">时间趋势分析</div>
                    <div class="step-question">问题是什么时候开始的？</div>
                </div>
            </div>
            <div class="chart-container">
                <canvas id="problemChart"></canvas>
            </div>
            <div class="answer-box warning">
                <div class="answer-title">结论</div>
                <div class="answer-value">问题从一开始就存在，不是某个时间点突然出现</div>
            </div>
        </div>

        <!-- Step 6: 月度对比 -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">6</div>
                <div>
                    <div class="step-title">月度对比分析</div>
                    <div class="step-question">哪些月份问题严重？为什么？</div>
                </div>
            </div>
            <table id="monthlyTable">
                <thead>
                    <tr>
                        <th>月份</th>
                        <th>VoV</th>
                        <th>STR</th>
                        <th>VOR</th>
                        <th>问题比例</th>
                        <th>诊断</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <div class="timeline" style="margin-top:30px;">
                <div class="timeline-item">
                    <strong>2025年7月</strong>：问题比例 22%（数据起点）
                </div>
                <div class="timeline-item bad">
                    <strong>2025年8-10月</strong>：问题恶化到 28-31%
                    <span class="badge badge-danger">主因: VOR↓9%</span>
                </div>
                <div class="timeline-item">
                    <strong>2025年11月</strong>：开始改善 27%
                </div>
                <div class="timeline-item good">
                    <strong>2025年12月</strong>：大幅改善到 10%
                    <span class="badge badge-success">原因: STR↑34%</span>
                </div>
                <div class="timeline-item bad">
                    <strong>2026年1月</strong>：回升到 18%
                    <span class="badge badge-warning">原因: STR↓10%</span>
                </div>
            </div>
        </div>

        <!-- Step 7: VoV 分解趋势 -->
        <div class="step">
            <div class="step-header">
                <div class="step-number">7</div>
                <div>
                    <div class="step-title">VoV 分解趋势</div>
                    <div class="step-question">STR、VOR 的变化趋势如何？</div>
                </div>
            </div>
            <div class="chart-container">
                <canvas id="decomposeChart"></canvas>
            </div>
            <p style="color:#666;margin-top:12px;">
                可以看到：12月 STR 明显上升（紫色线），问题比例随之下降
            </p>
        </div>

        <!-- 最终结论 -->
        <div class="conclusion">
            <h2>📋 最终结论与建议</h2>
            <ul>
                <li><strong>问题确认</strong>：低VoV高曝光问题 <span class="highlight">确实存在</span>，影响 35.7% 的头部曝光</li>
                <li><strong>根本原因</strong>：<span class="highlight">ROS 预估偏高 72%</span>，XGB 模型存在「回归均值」问题</li>
                <li><strong>时间规律</strong>：问题一直存在，8-10月最严重（VOR↓），12月改善（STR↑）</li>
                <li><strong>问题视频特征</strong>：<span class="highlight">低 STR</span> 的视频更容易出问题</li>
            </ul>
            <h3 style="margin-top:30px;margin-bottom:16px;">💡 建议</h3>
            <ul>
                <li><strong>短期</strong>：对真实 ROS < 2 的视频增加预估衰减系数</li>
                <li><strong>中期</strong>：改进 XGB 模型，解决「回归均值」问题</li>
                <li><strong>长期</strong>：考虑端到端 VoV 预估，避免三模型误差累积</li>
            </ul>
        </div>
    </div>

    <script>
        const dates = {json.dumps(dates)};
        const formattedDates = dates.map(d => d.slice(4,6) + '/' + d.slice(6,8));
        const problemData = {json.dumps(problem_data)};
        const strData = {json.dumps(str_data)};
        const vorData = {json.dumps(vor_data)};

        // 问题比例趋势图
        const problemColors = problemData.map(v => v > 25 ? '#e74c3c' : v > 15 ? '#f39c12' : '#27ae60');
        new Chart(document.getElementById('problemChart'), {{
            type: 'bar',
            data: {{
                labels: formattedDates,
                datasets: [{{
                    label: '问题比例 (%)',
                    data: problemData,
                    backgroundColor: problemColors,
                    borderRadius: 2
                }}]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {{
                    legend: {{ display: false }},
                    annotation: {{
                        annotations: {{
                            line1: {{
                                type: 'line',
                                yMin: 20, yMax: 20,
                                borderColor: '#e74c3c',
                                borderWidth: 2,
                                borderDash: [6, 6],
                                label: {{ display: true, content: '严重线 20%', position: 'end', backgroundColor: '#e74c3c' }}
                            }}
                        }}
                    }}
                }},
                scales: {{
                    y: {{ beginAtZero: true, max: 50, title: {{ display: true, text: '问题比例 (%)' }} }}
                }}
            }}
        }});

        // STR/VOR 分解图
        new Chart(document.getElementById('decomposeChart'), {{
            type: 'line',
            data: {{
                labels: formattedDates,
                datasets: [{{
                    label: 'STR (×100)',
                    data: strData,
                    borderColor: '#9b59b6',
                    tension: 0.3,
                    yAxisID: 'y'
                }}, {{
                    label: 'VOR',
                    data: vorData,
                    borderColor: '#f39c12',
                    tension: 0.3,
                    yAxisID: 'y1'
                }}]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: false,
                interaction: {{ mode: 'index', intersect: false }},
                plugins: {{ legend: {{ display: true, position: 'top' }} }},
                scales: {{
                    y: {{ type: 'linear', position: 'left', title: {{ display: true, text: 'STR (×100)' }} }},
                    y1: {{ type: 'linear', position: 'right', title: {{ display: true, text: 'VOR' }}, grid: {{ drawOnChartArea: false }} }}
                }}
            }}
        }});

        // 月度表格
        const monthlyData = {json.dumps(monthly_data)};
        const tbody = document.querySelector('#monthlyTable tbody');
        monthlyData.forEach(row => {{
            const tr = document.createElement('tr');
            if (row.problem > 25) tr.classList.add('problem');

            let diagnosis = '';
            if (row.problem <= 15) diagnosis = '<span class="badge badge-success">✓ 良好</span>';
            else if (row.vor < 6.2) diagnosis = '<span class="badge badge-danger">VOR↓</span>';
            else if (row.str < 0.045) diagnosis = '<span class="badge badge-danger">STR↓</span>';
            else diagnosis = '<span class="badge badge-warning">待分析</span>';

            tr.innerHTML = `
                <td>${{row.month}}</td>
                <td>${{row.vov.toFixed(3)}}</td>
                <td>${{row.str.toFixed(4)}}</td>
                <td>${{row.vor.toFixed(2)}}</td>
                <td>${{row.problem.toFixed(1)}}%</td>
                <td>${{diagnosis}}</td>
            `;
            tbody.appendChild(tr);
        }});
    </script>
</body>
</html>
'''

# 保存
html_path = output_dir / "分析报告.html"
with open(html_path, 'w', encoding='utf-8') as f:
    f.write(html_content)

print(f"分析报告已生成: {html_path}")
