"""
07_docking_visualization.py
分子对接结果可视化 + 更新综合报告
"""
import os, sys
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from rdkit import Chem
from rdkit.Chem import Descriptors, AllChem

BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DOCK = os.path.join(BASE, 'docking')
RESULTS = os.path.join(BASE, 'results')
FIGURES = os.path.join(RESULTS, 'figures')

os.makedirs(FIGURES, exist_ok=True)

plt.rcParams['font.family'] = 'Arial'
plt.rcParams['font.size'] = 11
plt.rcParams['axes.unicode_minus'] = False

# ============================================================
# 1. 读取对接结果
# ============================================================

docking_csv = os.path.join(DOCK, 'results', 'docking_results.csv')
desc_csv = os.path.join(DOCK, 'results', 'compound_descriptors.csv')

if os.path.exists(docking_csv):
    results = pd.read_csv(docking_csv)
    print(f'对接结果: {len(results)} 条')
    print(results.to_string())
else:
    print('对接结果文件不存在！')
    results = pd.DataFrame()

if os.path.exists(desc_csv):
    desc = pd.read_csv(desc_csv)
    print(f'\n分子描述符: {len(desc)} 条')
else:
    desc = pd.DataFrame()

# ============================================================
# 2. 分子描述符可视化
# ============================================================

if len(desc) > 0:
    fig, axes = plt.subplots(2, 3, figsize=(16, 10))
    
    metrics = ['MW', 'LogP', 'HBD', 'HBA', 'TPSA', 'Rotatable_Bonds']
    colors = ['#e74c3c', '#e67e22', '#f1c40f', '#2ecc71', '#3498db', '#9b59b6']
    
    for ax, metric, color in zip(axes.flat, metrics, colors):
        bars = ax.bar(desc['Compound'], desc[metric], color=color, alpha=0.75, edgecolor='grey', linewidth=0.5)
        ax.set_title(f'{metric}', fontsize=13, fontweight='bold')
        ax.set_xticklabels(desc['Compound'], rotation=45, ha='right', fontsize=7)
        ax.axhline(y=0, color='grey', linewidth=0.5)
        
        # 标注值
        for bar in bars:
            ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
                    f'{bar.get_height():.1f}', ha='center', va='bottom', fontsize=7)
    
    plt.tight_layout()
    plt.savefig(os.path.join(FIGURES, 'compound_descriptors.png'), dpi=200, bbox_inches='tight')
    plt.close()
    print('分子描述符图已保存')

# ============================================================
# 3. 对接热图
# ============================================================

if len(results) > 0:
    fig, ax = plt.subplots(figsize=(10, 7))
    
    pivot = results.pivot_table(index='Compound', columns='Target', values='Binding_Energy', aggfunc='first')
    
    # 排序
    pivot = pivot.reindex(desc.sort_values('Category')['Compound'].iloc[::-1] if len(desc) > 0 else pivot.index[::-1])
    
    # 热图
    sns.heatmap(pivot, annot=True, fmt='.1f', cmap='RdYlGn_r', center=-6.0,
                linewidths=1.5, ax=ax, cbar_kws={'label': 'Binding Energy (kcal/mol)'})
    
    ax.set_title('Molecular Docking Heatmap\n(发物活性成分 vs 核心靶点)', fontsize=14, fontweight='bold')
    ax.set_xlabel('Target Protein', fontsize=12)
    ax.set_ylabel('Compound', fontsize=12)
    
    plt.tight_layout()
    plt.savefig(os.path.join(FIGURES, 'docking_heatmap.png'), dpi=200, bbox_inches='tight')
    plt.close()
    print('对接热图已保存')
    
    # ============================================================
    # 4. 结合能柱状图
    # ============================================================
    
    fig, ax = plt.subplots(figsize=(14, 6))
    
    # 按化合物分组，按靶点显示
    colors_target = {'TNF': '#e74c3c', 'PTGS2': '#3498db', 'MAPK14': '#2ecc71', 
                     'NLRP3': '#f39c12', 'CASP1': '#9b59b6'}
    
    x = np.arange(len(results['Compound'].unique()))
    width = 0.15
    compounds = results['Compound'].unique()
    
    for i, (target, color) in enumerate(colors_target.items()):
        vals = []
        for comp in compounds:
            row = results[(results['Compound'] == comp) & (results['Target'] == target)]
            vals.append(row['Binding_Energy'].values[0] if len(row) > 0 else 0)
        ax.bar(x + i * width, vals, width, label=target, color=color, alpha=0.8, edgecolor='white')
    
    ax.axhline(y=-5.0, color='red', linestyle='--', alpha=0.5, label='Good binding (-5.0)')
    ax.axhline(y=-7.0, color='darkred', linestyle='--', alpha=0.3, label='Strong binding (-7.0)')
    
    ax.set_xticks(x + width * 2)
    ax.set_xticklabels(compounds, rotation=45, ha='right')
    ax.set_ylabel('Binding Energy (kcal/mol)', fontsize=12)
    ax.set_title('Molecular Docking Results by Target', fontsize=14, fontweight='bold')
    ax.legend(loc='lower right', fontsize=9)
    ax.set_ylim(results['Binding_Energy'].min() - 1, 0)
    
    plt.tight_layout()
    plt.savefig(os.path.join(FIGURES, 'docking_barplot.png'), dpi=200, bbox_inches='tight')
    plt.close()
    print('对接柱状图已保存')
    
    # ============================================================
    # 5. 类别-靶点热图（按类别汇总）
    # ============================================================
    
    cat_pivot = results.copy()
    cat_pivot['Category'] = cat_pivot['Compound'].map(
        dict(zip(desc['Compound'], desc['Category'])) if len(desc) > 0 else {})
    
    for _, row in results.iterrows():
        for _, d in desc.iterrows():
            if row['Compound'] == d['Compound']:
                cat_pivot.loc[cat_pivot['Compound'] == row['Compound'], 'Category'] = d['Category']
    
    # 按类别和靶点平均
    cat_avg = results.groupby(['Category', 'Target'])['Binding_Energy'].mean().unstack()
    
    fig, ax = plt.subplots(figsize=(8, 4))
    sns.heatmap(cat_avg, annot=True, fmt='.1f', cmap='RdYlGn_r', center=-6.0,
                linewidths=1.5, ax=ax, cbar_kws={'label': 'Avg Binding (kcal/mol)'})
    ax.set_title('Average Docking Score by Category', fontsize=14, fontweight='bold')
    plt.tight_layout()
    plt.savefig(os.path.join(FIGURES, 'docking_category_heatmap.png'), dpi=200, bbox_inches='tight')
    plt.close()
    print('类别-靶点热图已保存')

# ============================================================
# 5. GEO验证可视化
# ============================================================

geo_val_path = os.path.join(RESULTS, 'tables', 'GSE125532_validation.csv')
if os.path.exists(geo_val_path):
    val = pd.read_csv(geo_val_path)
    
    # 表达变化火山图风格
    fig, ax = plt.subplots(figsize=(12, 8))
    
    val['-log10(padj)'] = -np.log10(val['padj'].clip(lower=1e-50))
    
    colors = ['#e74c3c' if (v > 0.5 and s) else '#3498db' if (v < -0.5 and s) else '#95a5a6' 
              for v, s in zip(val['log2FC'], val['significant'])]
    sizes = [80 if s else 40 for s in val['significant']]
    
    scatter = ax.scatter(val['log2FC'], val['-log10(padj)'], c=colors, s=sizes, alpha=0.7, edgecolors='grey', linewidth=0.5)
    
    # 标注显著基因
    for _, row in val.iterrows():
        if row['significant']:
            ax.annotate(row['gene'], (row['log2FC'], row['-log10(padj)']),
                       fontsize=7, ha='left', va='bottom', alpha=0.8,
                       bbox=dict(boxstyle='round,pad=0.2', facecolor='yellow', alpha=0.3))
    
    ax.axhline(y=-np.log10(0.05), color='grey', linestyle='--', alpha=0.5)
    ax.axvline(x=0, color='grey', linestyle='-', alpha=0.3)
    ax.set_xlabel('log2(Fold Change) - GSE125532', fontsize=12)
    ax.set_ylabel('-log10(adjusted P-value)', fontsize=12)
    ax.set_title('GEO Validation: Intersection Targets in GSE125532\n(Chronic Otitis Media Effusion vs Blood)', 
                 fontsize=13, fontweight='bold')
    
    # 图例
    from matplotlib.lines import Line2D
    legend_elements = [
        Line2D([0], [0], marker='o', color='w', markerfacecolor='#e74c3c', markersize=10, label='Upregulated (sig)'),
        Line2D([0], [0], marker='o', color='w', markerfacecolor='#3498db', markersize=10, label='Downregulated (sig)'),
        Line2D([0], [0], marker='o', color='w', markerfacecolor='#95a5a6', markersize=10, label='Not significant'),
    ]
    ax.legend(handles=legend_elements, loc='upper right', fontsize=9)
    
    plt.tight_layout()
    plt.savefig(os.path.join(FIGURES, 'GEO125532_validation_volcano.png'), dpi=200, bbox_inches='tight')
    plt.close()
    print('GEO验证火山图已保存')

print('\n可视化完成！')
print(f'所有图表已保存到: {FIGURES}')
