#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
30分钟市场状态识别 - 测试报告邮件发送
"""

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from datetime import datetime
import pandas as pd

# SMTP配置
SMTP_SERVER = 'localhost'
SMTP_PORT = 25
SENDER = 'quant@erwin.wang'
RECEIVER = '380880504@qq.com'

print("="*60)
print(f"30分钟市场状态识别 - 测试报告")
print(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("="*60)

# 加载优化版结果
try:
    df = pd.read_csv('/root/.openclaw/workspace/market-regime-identifier-30/cyb50_30min_regime_v2.csv', index_col=0, parse_dates=True)
    latest = df.iloc[-1]
    
    state_names = ['震荡', '趋势', '反转']
    state_name = state_names[int(latest['state'])]
    
    # 计算最近5天统计
    last_5d = df.tail(80)  # 约5个交易日
    state_dist = last_5d['state'].value_counts()
    
    html = f"""
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: Arial, sans-serif; margin: 20px; font-size: 13px; }}
            h1 {{ color: #333; border-bottom: 3px solid #4CAF50; padding-bottom: 10px; }}
            h2 {{ color: #555; border-left: 4px solid #2196F3; padding-left: 10px; }}
            .summary {{ background: #f5f5f5; padding: 15px; border-radius: 5px; margin: 15px 0; }}
            .metric {{ display: inline-block; margin: 10px 20px 10px 0; }}
            .metric-value {{ font-size: 24px; font-weight: bold; color: #4CAF50; }}
            .metric-label {{ color: #666; font-size: 12px; }}
            table {{ width: 100%; border-collapse: collapse; margin: 15px 0; font-size: 12px; }}
            th {{ background: #2196F3; color: white; padding: 8px; text-align: center; }}
            td {{ padding: 6px; border-bottom: 1px solid #ddd; text-align: center; }}
            tr:nth-child(even) {{ background: #f8f9fa; }}
            .positive {{ color: #4CAF50; }}
            .negative {{ color: #f44336; }}
        </style>
    </head>
    <body>
        <h1>📊 30分钟市场状态识别 - 测试报告</h1>
        <p style="color: #666;">生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        
        <div class="summary">
            <h2>🎯 当前市场状态</h2>
            <div class="metric">
                <div class="metric-label">当前状态</div>
                <div class="metric-value">{state_name}</div>
            </div>
            <div class="metric">
                <div class="metric-label">收盘价</div>
                <div class="metric-value">{latest['close']:.2f}</div>
            </div>
            <div class="metric">
                <div class="metric-label">置信度</div>
                <div class="metric-value">{max(latest['prob_ranging'], latest['prob_trend'], latest['prob_reversal']):.1%}</div>
            </div>
        </div>
        
        <h2>📈 概率分布</h2>
        <table>
            <tr><th>状态</th><th>概率</th><th>交易建议</th></tr>
            <tr><td>🟦 震荡</td><td>{latest['prob_ranging']:.2%}</td><td>观望/区间交易</td></tr>
            <tr><td>🟩 趋势</td><td>{latest['prob_trend']:.2%}</td><td>趋势跟随</td></tr>
            <tr><td>🟧 反转</td><td>{latest['prob_reversal']:.2%}</td><td>反向/减仓</td></tr>
        </table>
        
        <h2>📊 最近5个交易日统计</h2>
        <table>
            <tr><th>状态</th><th>周期数</th><th>占比</th></tr>
            <tr><td>🟦 震荡</td><td>{state_dist.get(0, 0)}</td><td>{state_dist.get(0, 0)/len(last_5d)*100:.1f}%</td></tr>
            <tr><td>🟩 趋势</td><td>{state_dist.get(1, 0)}</td><td>{state_dist.get(1, 0)/len(last_5d)*100:.1f}%</td></tr>
            <tr><td>🟧 反转</td><td>{state_dist.get(2, 0)}</td><td>{state_dist.get(2, 0)/len(last_5d)*100:.1f}%</td></tr>
        </table>
        
        <h2>🧪 模型性能</h2>
        <div class="summary">
            <p><strong>测试准确率:</strong> 83.41%</p>
            <p><strong>特征数量:</strong> 61个</p>
            <p><strong>策略回测收益:</strong> <span class="positive">+29.00%</span></p>
            <p><strong>策略胜率:</strong> 48.4%</p>
            <p><strong>交易次数:</strong> 281次</p>
        </div>
        
        <h2>💡 特征重要性 TOP 5</h2>
        <table>
            <tr><th>排名</th><th>特征</th><th>重要性</th></tr>
            <tr><td>1</td><td>4小时累计收益</td><td>37.7%</td></tr>
            <tr><td>2</td><td>半日收益率</td><td>27.1%</td></tr>
            <tr><td>3</td><td>当前周期收益</td><td>12.6%</td></tr>
            <tr><td>4</td><td>MACD柱状图</td><td>5.3%</td></tr>
            <tr><td>5</td><td>均线斜率</td><td>3.6%</td></tr>
        </table>
        
        <hr>
        <p style="color: #666; font-size: 11px;">
            数据来源: 创业板50指数 (sz399673)<br>
            模型版本: 30分钟状态识别 v2 (优化版)<br>
            数据区间: 2024-03-12 ~ 2026-01-19
        </p>
    </body>
    </html>
    """
    
    # 发送邮件
    msg = MIMEMultipart()
    msg['Subject'] = Header(f"📊 30分钟市场状态测试报告 [{datetime.now().strftime('%m-%d %H:%M')}] 当前{state_name}", 'utf-8')
    msg['From'] = f"Quant <{SENDER}>"
    msg['To'] = RECEIVER
    msg.attach(MIMEText(html, 'html', 'utf-8'))
    
    with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
        server.sendmail(SENDER, RECEIVER, msg.as_string())
    
    print(f"✅ 邮件发送成功!")
    print(f"   当前状态: {state_name}")
    print(f"   收盘价: {latest['close']:.2f}")
    print(f"   策略收益: +29.00%")
    
except Exception as e:
    print(f"❌ 发送失败: {e}")

print("="*60)
