"""
灵感点分析结果可视化脚本

读取 how/灵感点 目录下的分析结果，结合作者历史帖子详情，生成可视化HTML页面
"""

import json
from pathlib import Path
from typing import Dict, Any, List, Optional
from datetime import datetime
import html as html_module


def load_inspiration_points_data(inspiration_dir: str) -> List[Dict[str, Any]]:
    """
    加载所有灵感点的分析结果

    Args:
        inspiration_dir: 灵感点目录路径

    Returns:
        灵感点分析结果列表
    """
    inspiration_path = Path(inspiration_dir)
    results = []

    # 遍历所有子目录
    for subdir in inspiration_path.iterdir():
        if subdir.is_dir():
            # 查找 all_summary 文件
            summary_files = list(subdir.glob("all_summary_*.json"))
            if summary_files:
                summary_file = summary_files[0]
                try:
                    with open(summary_file, 'r', encoding='utf-8') as f:
                        data = json.load(f)

                    # 加载完整的 step1 和 step2 数据
                    step1_data = None
                    step2_data = None

                    if "文件路径" in data:
                        step1_path = data["文件路径"].get("step1")
                        step2_path = data["文件路径"].get("step2")

                        if step1_path:
                            step1_full_path = Path(step1_path)
                            if not step1_full_path.is_absolute():
                                step1_full_path = inspiration_path.parent.parent.parent.parent / step1_path
                            if step1_full_path.exists():
                                with open(step1_full_path, 'r', encoding='utf-8') as f:
                                    step1_data = json.load(f)

                        if step2_path:
                            step2_full_path = Path(step2_path)
                            if not step2_full_path.is_absolute():
                                step2_full_path = inspiration_path.parent.parent.parent.parent / step2_path
                            if step2_full_path.exists():
                                with open(step2_full_path, 'r', encoding='utf-8') as f:
                                    step2_data = json.load(f)

                    results.append({
                        "summary": data,
                        "step1": step1_data,
                        "step2": step2_data,
                        "inspiration_name": subdir.name
                    })
                except Exception as e:
                    print(f"警告: 读取 {summary_file} 失败: {e}")

    return results


def load_posts_data(posts_dir: str) -> Dict[str, Dict[str, Any]]:
    """
    加载所有帖子详情数据

    Args:
        posts_dir: 帖子目录路径

    Returns:
        帖子ID到帖子详情的映射
    """
    posts_path = Path(posts_dir)
    posts_map = {}

    for post_file in posts_path.glob("*.json"):
        try:
            with open(post_file, 'r', encoding='utf-8') as f:
                post_data = json.load(f)
                post_id = post_data.get("channel_content_id")
                if post_id:
                    posts_map[post_id] = post_data
        except Exception as e:
            print(f"警告: 读取 {post_file} 失败: {e}")

    return posts_map


def generate_inspiration_card_html(inspiration_data: Dict[str, Any]) -> str:
    """
    生成单个灵感点的卡片HTML

    Args:
        inspiration_data: 灵感点数据

    Returns:
        HTML字符串
    """
    summary = inspiration_data.get("summary", {})
    step1 = inspiration_data.get("step1", {})
    step2 = inspiration_data.get("step2", {})
    inspiration_name = inspiration_data.get("inspiration_name", "未知灵感")

    # 提取关键指标
    metrics = summary.get("关键指标", {})
    step1_score = metrics.get("step1_top1_score", 0)
    step2_score = metrics.get("step2_score", 0)
    step1_match_element = metrics.get("step1_top1_匹配要素", "")
    step2_increment_count = metrics.get("step2_增量词数量", 0)

    # 确定卡片颜色（基于Step1分数）
    if step1_score >= 0.7:
        border_color = "#10b981"
        step1_color = "#10b981"
    elif step1_score >= 0.5:
        border_color = "#f59e0b"
        step1_color = "#f59e0b"
    elif step1_score >= 0.3:
        border_color = "#3b82f6"
        step1_color = "#3b82f6"
    else:
        border_color = "#ef4444"
        step1_color = "#ef4444"

    # Step2颜色
    if step2_score >= 0.7:
        step2_color = "#10b981"
    elif step2_score >= 0.5:
        step2_color = "#f59e0b"
    elif step2_score >= 0.3:
        step2_color = "#3b82f6"
    else:
        step2_color = "#ef4444"

    # 转义HTML
    inspiration_name_escaped = html_module.escape(inspiration_name)
    step1_match_element_escaped = html_module.escape(step1_match_element)

    # 获取Step1匹配结果（简要展示）
    step1_matches = step1.get("匹配结果", []) if step1 else []
    step1_match_preview = ""
    if step1_matches:
        top_match = step1_matches[0]
        element_name = top_match.get("要素", {}).get("名称", "")
        match_score = top_match.get("分数", 0)
        step1_match_preview = f'''
        <div class="match-preview">
            <div class="match-preview-header">🎯 Step1 Top1匹配</div>
            <div class="match-preview-content">
                <span class="match-preview-name">{html_module.escape(element_name)}</span>
                <span class="match-preview-score" style="color: {step1_color};">{match_score:.2f}</span>
            </div>
        </div>
        '''

    # 获取Step2匹配结果（简要展示）
    step2_matches = step2.get("匹配结果", []) if step2 else []
    step2_match_preview = ""
    if step2_matches:
        top_match = step2_matches[0]
        words = top_match.get("增量词", [])
        match_score = top_match.get("分数", 0)
        step2_match_preview = f'''
        <div class="match-preview">
            <div class="match-preview-header">➕ Step2 Top1增量词</div>
            <div class="match-preview-content">
                <span class="match-preview-name">{html_module.escape(", ".join(words))}</span>
                <span class="match-preview-score" style="color: {step2_color};">{match_score:.2f}</span>
            </div>
        </div>
        '''

    # 准备详细数据用于弹窗
    detail_data_json = json.dumps(inspiration_data, ensure_ascii=False)
    detail_data_json_escaped = html_module.escape(detail_data_json)

    html = f'''
    <div class="inspiration-card" style="border-left-color: {border_color};"
         data-inspiration-name="{inspiration_name_escaped}"
         data-detail="{detail_data_json_escaped}"
         data-step1-score="{step1_score}"
         data-step2-score="{step2_score}"
         onclick="showInspirationDetail(this)">
        <div class="card-header">
            <h3 class="inspiration-name">{inspiration_name_escaped}</h3>
        </div>

        <div class="score-section">
            <div class="score-item">
                <div class="score-label">Step1分数</div>
                <div class="score-value" style="color: {step1_color};">{step1_score:.3f}</div>
            </div>
            <div class="score-divider"></div>
            <div class="score-item">
                <div class="score-label">Step2分数</div>
                <div class="score-value" style="color: {step2_color};">{step2_score:.3f}</div>
            </div>
        </div>

        {step1_match_preview}
        {step2_match_preview}

        <div class="metrics-section">
            <div class="metric-item">
                <span class="metric-icon">📊</span>
                <span class="metric-label">增量词数:</span>
                <span class="metric-value">{step2_increment_count}</span>
            </div>
        </div>

        <div class="click-hint">点击查看详情 →</div>
    </div>
    '''

    return html


def generate_detail_modal_content_js() -> str:
    """
    生成详情弹窗内容的JavaScript函数

    Returns:
        JavaScript代码字符串
    """
    return '''
    function showInspirationDetail(element) {
        const inspirationName = element.dataset.inspirationName;
        const detailStr = element.dataset.detail;

        let detail;
        try {
            detail = JSON.parse(detailStr);
        } catch(e) {
            console.error('解析数据失败:', e);
            return;
        }

        const modal = document.getElementById('detailModal');
        const modalBody = document.getElementById('modalBody');

        const summary = detail.summary || {};
        const step1 = detail.step1 || {};
        const step2 = detail.step2 || {};
        const metrics = summary.关键指标 || {};

        // 构建Modal内容
        let content = `
            <div class="modal-header">
                <h2 class="modal-title">${inspirationName}</h2>
            </div>
        `;

        // 元数据信息
        const metadata = summary.元数据 || {};
        if (metadata.current_time || metadata.流程) {
            content += `
                <div class="modal-section">
                    <h3>📋 分析信息</h3>
                    <div class="info-grid">
                        ${metadata.current_time ? `<div class="info-item"><span class="info-label">分析时间:</span> <span class="info-value">${metadata.current_time}</span></div>` : ''}
                        ${metadata.流程 ? `<div class="info-item"><span class="info-label">分析流程:</span> <span class="info-value">${metadata.流程}</span></div>` : ''}
                        ${metadata.step1_model ? `<div class="info-item"><span class="info-label">Step1模型:</span> <span class="info-value">${metadata.step1_model}</span></div>` : ''}
                        ${metadata.step2_model ? `<div class="info-item"><span class="info-label">Step2模型:</span> <span class="info-value">${metadata.step2_model}</span></div>` : ''}
                    </div>
                </div>
            `;
        }

        // 关键指标
        content += `
            <div class="modal-section">
                <h3>📊 关键指标</h3>
                <div class="metrics-grid">
                    <div class="metric-box">
                        <div class="metric-box-label">Step1得分</div>
                        <div class="metric-box-value">${metrics.step1_top1_score || 0}</div>
                    </div>
                    <div class="metric-box">
                        <div class="metric-box-label">Step2得分</div>
                        <div class="metric-box-value">${metrics.step2_score || 0}</div>
                    </div>
                    <div class="metric-box">
                        <div class="metric-box-label">增量词数量</div>
                        <div class="metric-box-value">${metrics.step2_增量词数量 || 0}</div>
                    </div>
                    <div class="metric-box wide">
                        <div class="metric-box-label">匹配要素</div>
                        <div class="metric-box-value small">${metrics.step1_top1_匹配要素 || '无'}</div>
                    </div>
                </div>
            </div>
        `;

        // Step1 详细信息
        if (step1 && step1.灵感) {
            const inspiration = step1.灵感 || '';
            const persona = step1.人设 || {};
            const matches = step1.匹配结果 || [];

            content += `
                <div class="modal-section">
                    <h3>🎯 Step1: 灵感人设匹配</h3>
                    <div class="step-content">
                        <div class="step-field">
                            <span class="step-field-label">灵感内容:</span>
                            <span class="step-field-value">${inspiration}</span>
                        </div>
            `;

            // 显示匹配结果（Top3）
            if (matches.length > 0) {
                content += `
                    <div class="step-field">
                        <span class="step-field-label">匹配结果 (Top ${Math.min(3, matches.length)}):</span>
                        <div class="matches-list">
                `;

                matches.slice(0, 3).forEach((match, index) => {
                    const element = match.要素 || {};
                    const score = match.分数 || 0;
                    const reason = match.原因 || '';
                    const colorClass = index === 0 ? 'top1' : (index === 1 ? 'top2' : 'top3');

                    content += `
                        <div class="match-item ${colorClass}">
                            <div class="match-header">
                                <span class="match-rank">#${index + 1}</span>
                                <span class="match-element-name">${element.名称 || '未知要素'}</span>
                                <span class="match-score">${score.toFixed(2)}</span>
                            </div>
                            ${element.定义 ? `<div class="match-detail"><strong>定义:</strong> ${element.定义}</div>` : ''}
                            <div class="match-reason">${reason}</div>
                        </div>
                    `;
                });

                content += `
                        </div>
                    </div>
                `;
            }

            content += `
                    </div>
                </div>
            `;
        }

        // Step2 详细信息
        if (step2 && step2.灵感) {
            const step2Matches = step2.匹配结果 || [];

            content += `
                <div class="modal-section">
                    <h3>➕ Step2: 增量词匹配</h3>
                    <div class="step-content">
            `;

            if (step2Matches.length > 0) {
                content += `
                    <div class="step-field">
                        <span class="step-field-label">增量词匹配结果:</span>
                        <div class="increment-matches">
                `;

                step2Matches.forEach((match, index) => {
                    const words = match.增量词 || [];
                    const score = match.分数 || 0;
                    const reason = match.原因 || '';

                    content += `
                        <div class="increment-item">
                            <div class="increment-header">
                                <span class="increment-words">${words.join(', ')}</span>
                                <span class="increment-score">${score.toFixed(2)}</span>
                            </div>
                            <div class="increment-reason">${reason}</div>
                        </div>
                    `;
                });

                content += `
                        </div>
                    </div>
                `;
            } else {
                content += `
                    <div class="empty-state">暂无增量词匹配结果</div>
                `;
            }

            content += `
                    </div>
                </div>
            `;
        }

        // 日志链接
        if (metadata.log_url) {
            content += `
                <div class="modal-link">
                    <a href="${metadata.log_url}" target="_blank" class="modal-link-btn">
                        🔗 查看详细日志
                    </a>
                </div>
            `;
        }

        modalBody.innerHTML = content;
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        const modal = document.getElementById('detailModal');
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }

    function closeModalOnOverlay(event) {
        if (event.target.id === 'detailModal') {
            closeModal();
        }
    }

    // ESC键关闭Modal
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeModal();
        }
    });

    // 搜索和过滤功能
    function filterInspirations() {
        const searchInput = document.getElementById('searchInput').value.toLowerCase();
        const sortSelect = document.getElementById('sortSelect').value;
        const cards = document.querySelectorAll('.inspiration-card');

        let visibleCards = Array.from(cards);

        // 搜索过滤
        visibleCards.forEach(card => {
            const name = card.dataset.inspirationName.toLowerCase();
            if (name.includes(searchInput)) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });

        // 获取可见的卡片
        visibleCards = Array.from(cards).filter(card => card.style.display !== 'none');

        // 排序
        if (sortSelect === 'score-desc' || sortSelect === 'score-asc') {
            visibleCards.sort((a, b) => {
                const detailA = JSON.parse(a.dataset.detail);
                const detailB = JSON.parse(b.dataset.detail);
                const scoreA = ((detailA.summary.关键指标.step1_top1_score || 0) + (detailA.summary.关键指标.step2_score || 0)) / 2;
                const scoreB = ((detailB.summary.关键指标.step1_top1_score || 0) + (detailB.summary.关键指标.step2_score || 0)) / 2;
                return sortSelect === 'score-desc' ? scoreB - scoreA : scoreA - scoreB;
            });
        } else if (sortSelect === 'name-asc' || sortSelect === 'name-desc') {
            visibleCards.sort((a, b) => {
                const nameA = a.dataset.inspirationName;
                const nameB = b.dataset.inspirationName;
                return sortSelect === 'name-asc' ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA);
            });
        }

        // 重新排列卡片
        const container = document.querySelector('.inspirations-grid');
        visibleCards.forEach(card => {
            container.appendChild(card);
        });

        // 更新统计
        updateStats();
    }

    function updateStats() {
        const cards = document.querySelectorAll('.inspiration-card');
        const visibleCards = Array.from(cards).filter(card => card.style.display !== 'none');

        document.getElementById('totalCount').textContent = visibleCards.length;

        let excellentCount = 0;
        let goodCount = 0;
        let normalCount = 0;
        let needOptCount = 0;
        let totalScore = 0;

        visibleCards.forEach(card => {
            const detail = JSON.parse(card.dataset.detail);
            const metrics = detail.summary.关键指标;
            const score = ((metrics.step1_top1_score || 0) + (metrics.step2_score || 0)) / 2 * 100;
            totalScore += score;

            if (score >= 70) excellentCount++;
            else if (score >= 50) goodCount++;
            else if (score >= 30) normalCount++;
            else needOptCount++;
        });

        document.getElementById('excellentCount').textContent = excellentCount;
        document.getElementById('goodCount').textContent = goodCount;
        document.getElementById('normalCount').textContent = normalCount;
        document.getElementById('needOptCount').textContent = needOptCount;

        const avgScore = visibleCards.length > 0 ? (totalScore / visibleCards.length).toFixed(1) : 0;
        document.getElementById('avgScore').textContent = avgScore;
    }
    '''


def generate_html(
    inspirations_data: List[Dict[str, Any]],
    posts_map: Dict[str, Dict[str, Any]],
    output_path: str
) -> str:
    """
    生成完整的可视化HTML

    Args:
        inspirations_data: 灵感点数据列表
        posts_map: 帖子数据映射
        output_path: 输出文件路径

    Returns:
        输出文件路径
    """
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 统计信息
    total_count = len(inspirations_data)
    excellent_count = sum(1 for d in inspirations_data
                         if ((d["summary"].get("关键指标", {}).get("step1_top1_score", 0) +
                              d["summary"].get("关键指标", {}).get("step2_score", 0)) / 2 * 100) >= 70)
    good_count = sum(1 for d in inspirations_data
                    if 50 <= ((d["summary"].get("关键指标", {}).get("step1_top1_score", 0) +
                               d["summary"].get("关键指标", {}).get("step2_score", 0)) / 2 * 100) < 70)
    normal_count = sum(1 for d in inspirations_data
                      if 30 <= ((d["summary"].get("关键指标", {}).get("step1_top1_score", 0) +
                                 d["summary"].get("关键指标", {}).get("step2_score", 0)) / 2 * 100) < 50)
    need_opt_count = sum(1 for d in inspirations_data
                        if ((d["summary"].get("关键指标", {}).get("step1_top1_score", 0) +
                             d["summary"].get("关键指标", {}).get("step2_score", 0)) / 2 * 100) < 30)

    total_score = sum((d["summary"].get("关键指标", {}).get("step1_top1_score", 0) +
                       d["summary"].get("关键指标", {}).get("step2_score", 0)) / 2 * 100
                     for d in inspirations_data)
    avg_score = total_score / total_count if total_count > 0 else 0

    # 按综合分数排序
    inspirations_data_sorted = sorted(
        inspirations_data,
        key=lambda x: (x["summary"].get("关键指标", {}).get("step1_top1_score", 0) +
                      x["summary"].get("关键指标", {}).get("step2_score", 0)) / 2,
        reverse=True
    )

    # 生成卡片HTML
    cards_html = [generate_inspiration_card_html(data) for data in inspirations_data_sorted]
    cards_html_str = '\n'.join(cards_html)

    # 生成JavaScript
    detail_modal_js = generate_detail_modal_content_js()

    # 完整HTML
    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>灵感点分析可视化</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}

        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
        }}

        .container {{
            max-width: 1600px;
            margin: 0 auto;
        }}

        .header {{
            background: white;
            padding: 40px;
            border-radius: 16px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }}

        .header h1 {{
            font-size: 42px;
            margin-bottom: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-weight: 800;
        }}

        .header-subtitle {{
            font-size: 16px;
            color: #6b7280;
            margin-bottom: 30px;
        }}

        .stats-overview {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 20px;
            margin-top: 25px;
        }}

        .stat-box {{
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            transition: transform 0.3s ease;
        }}

        .stat-box:hover {{
            transform: translateY(-5px);
        }}

        .stat-label {{
            font-size: 13px;
            color: #6b7280;
            margin-bottom: 8px;
            font-weight: 600;
        }}

        .stat-value {{
            font-size: 32px;
            font-weight: 700;
            color: #1a1a1a;
        }}

        .stat-box.excellent .stat-value {{
            color: #10b981;
        }}

        .stat-box.good .stat-value {{
            color: #f59e0b;
        }}

        .stat-box.normal .stat-value {{
            color: #3b82f6;
        }}

        .stat-box.need-opt .stat-value {{
            color: #ef4444;
        }}

        .controls-section {{
            background: white;
            padding: 25px;
            border-radius: 16px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            align-items: center;
        }}

        .search-box {{
            flex: 1;
            min-width: 250px;
        }}

        .search-input {{
            width: 100%;
            padding: 12px 20px;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            font-size: 15px;
            transition: all 0.3s;
        }}

        .search-input:focus {{
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }}

        .sort-box {{
            display: flex;
            align-items: center;
            gap: 12px;
        }}

        .sort-label {{
            font-size: 14px;
            font-weight: 600;
            color: #374151;
        }}

        .sort-select {{
            padding: 10px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            font-size: 14px;
            background: white;
            cursor: pointer;
            transition: all 0.3s;
        }}

        .sort-select:focus {{
            outline: none;
            border-color: #667eea;
        }}

        .inspirations-section {{
            background: white;
            padding: 30px;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
        }}

        .inspirations-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
            gap: 25px;
        }}

        .inspiration-card {{
            background: white;
            border-radius: 14px;
            padding: 25px;
            border-left: 6px solid #10b981;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            position: relative;
        }}

        .inspiration-card:hover {{
            transform: translateY(-8px);
            box-shadow: 0 12px 30px rgba(102, 126, 234, 0.2);
        }}

        .card-header {{
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 20px;
            gap: 12px;
        }}

        .inspiration-name {{
            font-size: 19px;
            font-weight: 700;
            color: #1a1a1a;
            line-height: 1.4;
            flex: 1;
        }}

        .grade-badge {{
            background: #10b981;
            color: white;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 700;
            white-space: nowrap;
        }}

        .score-section {{
            display: flex;
            align-items: center;
            gap: 25px;
            margin-bottom: 20px;
            padding: 20px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 12px;
        }}

        .main-score {{
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }}

        .score-circle {{
            width: 90px;
            height: 90px;
            border-radius: 50%;
            border: 6px solid #10b981;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
        }}

        .score-value {{
            font-size: 26px;
            font-weight: 800;
            color: #10b981;
        }}

        .score-label {{
            font-size: 12px;
            color: #6b7280;
            font-weight: 600;
        }}

        .sub-scores {{
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }}

        .sub-score-item {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            background: white;
            border-radius: 8px;
        }}

        .sub-score-label {{
            font-size: 13px;
            color: #6b7280;
            font-weight: 600;
        }}

        .sub-score-value {{
            font-size: 18px;
            font-weight: 700;
            color: #2563eb;
        }}

        .metrics-section {{
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 15px;
        }}

        .metric-item {{
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: #4b5563;
        }}

        .metric-icon {{
            font-size: 16px;
        }}

        .metric-label {{
            font-weight: 600;
        }}

        .metric-value {{
            color: #1f2937;
        }}

        .click-hint {{
            position: absolute;
            bottom: 15px;
            right: 15px;
            font-size: 12px;
            color: #8b5cf6;
            font-weight: 700;
            opacity: 0;
            transition: opacity 0.3s ease;
            background: rgba(139, 92, 246, 0.1);
            padding: 6px 12px;
            border-radius: 8px;
        }}

        .inspiration-card:hover .click-hint {{
            opacity: 1;
        }}

        /* Modal样式 */
        .modal-overlay {{
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
            overflow-y: auto;
        }}

        .modal-overlay.active {{
            display: flex;
        }}

        .modal-content {{
            background: white;
            border-radius: 16px;
            max-width: 1200px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
        }}

        .modal-close {{
            position: sticky;
            top: 0;
            right: 0;
            background: white;
            border: none;
            font-size: 32px;
            color: #6b7280;
            cursor: pointer;
            padding: 15px 20px;
            z-index: 10;
            text-align: right;
            border-bottom: 1px solid #e5e7eb;
        }}

        .modal-close:hover {{
            color: #1f2937;
        }}

        .modal-body {{
            padding: 30px;
        }}

        .modal-header {{
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e5e7eb;
        }}

        .modal-title {{
            font-size: 28px;
            font-weight: 800;
            color: #1a1a1a;
        }}

        .modal-section {{
            margin-bottom: 30px;
        }}

        .modal-section h3 {{
            font-size: 20px;
            font-weight: 700;
            color: #374151;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f3f4f6;
        }}

        .info-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }}

        .info-item {{
            background: #f9fafb;
            padding: 12px 16px;
            border-radius: 8px;
            border-left: 3px solid #8b5cf6;
        }}

        .info-label {{
            font-weight: 600;
            color: #6b7280;
            font-size: 13px;
            margin-right: 8px;
        }}

        .info-value {{
            color: #1f2937;
            font-size: 14px;
        }}

        .metrics-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }}

        .metric-box {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            color: white;
        }}

        .metric-box.wide {{
            grid-column: span 2;
        }}

        .metric-box-label {{
            font-size: 13px;
            opacity: 0.9;
            margin-bottom: 8px;
            font-weight: 600;
        }}

        .metric-box-value {{
            font-size: 28px;
            font-weight: 700;
        }}

        .metric-box-value.small {{
            font-size: 16px;
        }}

        .step-content {{
            background: #f9fafb;
            padding: 20px;
            border-radius: 12px;
        }}

        .step-field {{
            margin-bottom: 20px;
        }}

        .step-field-label {{
            font-weight: 700;
            color: #374151;
            font-size: 14px;
            margin-bottom: 8px;
            display: block;
        }}

        .step-field-value {{
            color: #1f2937;
            font-size: 15px;
            line-height: 1.7;
        }}

        .matches-list {{
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-top: 10px;
        }}

        .match-item {{
            background: white;
            padding: 18px;
            border-radius: 10px;
            border-left: 5px solid #3b82f6;
        }}

        .match-item.top1 {{
            border-left-color: #fbbf24;
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 50%, white 100%);
        }}

        .match-item.top2 {{
            border-left-color: #c0c0c0;
            background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 50%, white 100%);
        }}

        .match-item.top3 {{
            border-left-color: #cd7f32;
            background: linear-gradient(135deg, #fef3c7 0%, #fed7aa 50%, white 100%);
        }}

        .match-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            gap: 10px;
        }}

        .match-rank {{
            font-size: 18px;
            font-weight: 800;
            color: #6b7280;
        }}

        .match-element-name {{
            flex: 1;
            font-size: 16px;
            font-weight: 700;
            color: #1f2937;
        }}

        .match-score {{
            font-size: 22px;
            font-weight: 800;
            color: #2563eb;
            background: white;
            padding: 6px 14px;
            border-radius: 8px;
        }}

        .match-detail {{
            background: rgba(255, 255, 255, 0.7);
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 10px;
            font-size: 13px;
            color: #4b5563;
        }}

        .match-reason {{
            color: #1f2937;
            font-size: 14px;
            line-height: 1.7;
        }}

        .increment-matches {{
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-top: 10px;
        }}

        .increment-item {{
            background: white;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #10b981;
        }}

        .increment-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }}

        .increment-words {{
            font-weight: 700;
            color: #1f2937;
            font-size: 15px;
        }}

        .increment-score {{
            font-size: 20px;
            font-weight: 800;
            color: #10b981;
        }}

        .increment-reason {{
            color: #4b5563;
            font-size: 13px;
            line-height: 1.6;
        }}

        .empty-state {{
            text-align: center;
            padding: 40px;
            color: #9ca3af;
            font-size: 14px;
        }}

        .modal-link {{
            margin-top: 25px;
            padding-top: 20px;
            border-top: 2px solid #e5e7eb;
            text-align: center;
        }}

        .modal-link-btn {{
            display: inline-flex;
            align-items: center;
            gap: 10px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            text-decoration: none;
            border-radius: 10px;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.3s;
        }}

        .modal-link-btn:hover {{
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
        }}

        .timestamp {{
            text-align: center;
            color: white;
            font-size: 13px;
            margin-top: 30px;
            opacity: 0.8;
        }}

        @media (max-width: 768px) {{
            .inspirations-grid {{
                grid-template-columns: 1fr;
            }}

            .header h1 {{
                font-size: 32px;
            }}

            .stats-overview {{
                grid-template-columns: repeat(2, 1fr);
            }}
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>💡 灵感点分析可视化</h1>
            <div class="header-subtitle">基于HOW人设的灵感点匹配分析结果</div>

            <div class="stats-overview">
                <div class="stat-box">
                    <div class="stat-label">分析总数</div>
                    <div class="stat-value" id="totalCount">{total_count}</div>
                </div>
                <div class="stat-box excellent">
                    <div class="stat-label">优秀 (≥70)</div>
                    <div class="stat-value" id="excellentCount">{excellent_count}</div>
                </div>
                <div class="stat-box good">
                    <div class="stat-label">良好 (50-70)</div>
                    <div class="stat-value" id="goodCount">{good_count}</div>
                </div>
                <div class="stat-box normal">
                    <div class="stat-label">一般 (30-50)</div>
                    <div class="stat-value" id="normalCount">{normal_count}</div>
                </div>
                <div class="stat-box need-opt">
                    <div class="stat-label">待优化 (<30)</div>
                    <div class="stat-value" id="needOptCount">{need_opt_count}</div>
                </div>
                <div class="stat-box">
                    <div class="stat-label">平均分数</div>
                    <div class="stat-value" id="avgScore">{avg_score:.1f}</div>
                </div>
            </div>
        </div>

        <div class="controls-section">
            <div class="search-box">
                <input type="text"
                       id="searchInput"
                       class="search-input"
                       placeholder="🔍 搜索灵感点名称..."
                       oninput="filterInspirations()">
            </div>

            <div class="sort-box">
                <span class="sort-label">排序方式:</span>
                <select id="sortSelect" class="sort-select" onchange="filterInspirations()">
                    <option value="score-desc">分数从高到低</option>
                    <option value="score-asc">分数从低到高</option>
                    <option value="name-asc">名称A-Z</option>
                    <option value="name-desc">名称Z-A</option>
                </select>
            </div>
        </div>

        <div class="inspirations-section">
            <div class="inspirations-grid">
                {cards_html_str}
            </div>
        </div>

        <div class="timestamp">生成时间: {timestamp}</div>

        <!-- Modal -->
        <div id="detailModal" class="modal-overlay" onclick="closeModalOnOverlay(event)">
            <div class="modal-content">
                <button class="modal-close" onclick="closeModal()">&times;</button>
                <div class="modal-body" id="modalBody">
                    <!-- Content will be inserted here -->
                </div>
            </div>
        </div>
    </div>

    <script>
    {detail_modal_js}
    </script>
</body>
</html>'''

    # 写入文件
    output_file = Path(output_path)
    output_file.parent.mkdir(parents=True, exist_ok=True)

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)

    return str(output_file.absolute())


def main():
    """主函数"""
    import sys

    # 配置路径
    inspiration_dir = "/Users/semsevens/Desktop/workspace/aaa/dev_3/data/阿里多多酱/out/人设_1110/how/灵感点"
    posts_dir = "/Users/semsevens/Desktop/workspace/aaa/dev_3/data/阿里多多酱/作者历史帖子"
    output_path = "/Users/semsevens/Desktop/workspace/aaa/dev_3/data/阿里多多酱/out/人设_1110/how/灵感点可视化.html"

    print("=" * 60)
    print("灵感点分析可视化脚本")
    print("=" * 60)

    # 加载数据
    print("\n📂 正在加载灵感点数据...")
    inspirations_data = load_inspiration_points_data(inspiration_dir)
    print(f"✅ 成功加载 {len(inspirations_data)} 个灵感点")

    print("\n📂 正在加载帖子数据...")
    posts_map = load_posts_data(posts_dir)
    print(f"✅ 成功加载 {len(posts_map)} 个帖子")

    # 生成HTML
    print("\n🎨 正在生成可视化HTML...")
    result_path = generate_html(inspirations_data, posts_map, output_path)

    print(f"\n✅ 可视化文件已生成!")
    print(f"📄 文件路径: {result_path}")
    print(f"\n💡 在浏览器中打开该文件即可查看可视化结果")
    print("=" * 60)


if __name__ == "__main__":
    main()
