import json
import os
from datetime import datetime, timezone, timedelta
from pathlib import Path
import sys

# 确保导入路径
import sys
from pathlib import Path

# 获取项目根目录
ROOT = Path(__file__).parent.parent.absolute()
LOGS_DIR = ROOT / "logs"

if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from src.agent_role_router import call_llm, ROLE_TREND_ANALYST

# 真正的 AI 调用
def ask_deepseek_review(trade_data):
    """
    trade_data 示例: {
        "side": "BUY",
        "pnl": 2.36,
        "evidence": ["ema9_gt_ema21", "llm_calibrated:0.8"],
        "symbol": "XAUUSD"
    }
    """
    side_zh = "看多 (BUY)" if trade_data['side'] == "BUY" else "看空 (SELL)"
    pnl_str = f"+${trade_data['pnl']}" if trade_data['pnl'] > 0 else f"-${abs(trade_data['pnl'])}"
    
    prompt = f"""
    请作为一名资深的黄金交易风控官，分析并复盘以下这笔交易：
    交易品种: {trade_data['symbol']}
    交易方向: {side_zh}
    最终盈亏: {pnl_str}
    系统决策证据: {', '.join(trade_data['evidence'])}
    
    请用专业、简练的口吻写一段复盘分析（约 100 字），说明系统是如何捕捉信号的，以及这笔交易在风控和策略上的执行亮点。
    如果是盈利，请点出策略的有效性；如果是亏损，请点出风控的保护作用。
    """
    
    try:
        review = call_llm(
            role=ROLE_TREND_ANALYST,
            prompt=prompt,
            temperature=0.7,
            max_tokens=500
        )
        return review.strip()
    except Exception as e:
        print(f"AI 调用失败: {e}")
        # Fallback 模拟
        return f"本次交易执行了 {trade_data['symbol']} 的{side_zh}策略。系统捕捉到了 {', '.join(trade_data['evidence'])} 的信号组合。在波动率受控的前提下，实现了 {pnl_str} 的收益，验证了 AI 决策链在微观结构捕捉上的有效性。"

def generate_audit_report():
    trading_ledger = LOGS_DIR / "trading_ledger.ndjson"
    decision_ledger = LOGS_DIR / "decision_ledger.ndjson"
    reports_dir = ROOT / "website" / "reports"
    reports_dir.mkdir(parents=True, exist_ok=True)

    if not trading_ledger.exists():
        print("未找到交易账本，无法生成报告。")
        return

    # 1. 提取最近的平仓记录
    trades = []
    with open(trading_ledger, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in reversed(lines):
            try:
                data = json.loads(line)
                if data.get("action") == "CLOSE" or data.get("pnl") != 0:
                    trades.append(data)
                if len(trades) >= 5: # 只取最近5笔
                    break
            except: continue

    # 2. 匹配决策证据
    decisions = {}
    if decision_ledger.exists():
        with open(decision_ledger, 'r', encoding='utf-8') as f:
            for line in f:
                try:
                    d = json.loads(line)
                    if d.get("category") == "signal_envelope":
                        sig = d.get("payload", {}).get("signal", {})
                        decisions[sig.get("signal_id")] = sig.get("trace", {})
                except: continue

    # 3. 组装数据并调用 AI 复盘
    audit_items = []
    for t in trades:
        trace = decisions.get(t.get("signal_id"), {})
        evidence = trace.get("evidence", ["趋势跟踪策略"])
        
        ai_review = ask_deepseek_review({
            "side": t.get("side"),
            "pnl": t.get("pnl"),
            "evidence": evidence,
            "symbol": t.get("symbol", "XAUUSD")
        })
        
        audit_items.append({
            "ts": t.get("ts")[:16].replace("T", " "),
            "side": t.get("side"),
            "pnl": t.get("pnl"),
            "pnl_class": "profit" if t.get("pnl", 0) > 0 else "loss",
            "review": ai_review,
            "evidence": evidence
        })

    # 4. 渲染 HTML 模板 (机构级深色系)
    html_template = f"""
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <style>
            :root {{
                --bg: #020617;
                --card: #0f172a;
                --gold: #d4a017;
                --profit: #22c55e;
                --loss: #ef4444;
                --text: #f8fafc;
                --text-dim: #94a3b8;
            }}
            body {{ font-family: 'Inter', system-ui, sans-serif; background: var(--bg); color: var(--text); padding: 40px; line-height: 1.6; }}
            .header {{ border-left: 4px solid var(--gold); padding-left: 20px; margin-bottom: 40px; }}
            .header h1 {{ font-size: 24px; margin: 0; letter-spacing: 1px; }}
            .header p {{ color: var(--text-dim); font-size: 14px; margin-top: 5px; }}
            .audit-card {{ background: var(--card); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; padding: 24px; margin-bottom: 20px; position: relative; overflow: hidden; }}
            .audit-card::before {{ content: ""; position: absolute; top: 0; left: 0; width: 4px; height: 100%; background: var(--gold); opacity: 0.3; }}
            .meta {{ display: flex; justify-content: space-between; font-size: 12px; color: var(--text-dim); margin-bottom: 12px; font-family: monospace; }}
            .pnl-badge {{ font-size: 20px; font-weight: bold; margin-bottom: 15px; }}
            .profit {{ color: var(--profit); }}
            .loss {{ color: var(--loss); }}
            .review {{ background: rgba(0,0,0,0.2); padding: 15px; border-radius: 8px; font-size: 14px; border-left: 2px solid rgba(212, 160, 23, 0.5); }}
            .evidence-tags {{ margin-top: 10px; display: flex; gap: 8px; flex-wrap: wrap; }}
            .tag {{ font-size: 10px; background: rgba(255,255,255,0.05); padding: 2px 8px; border-radius: 4px; color: var(--gold); border: 1px solid rgba(212,160,23,0.2); }}
            .footer {{ text-align: center; margin-top: 60px; font-size: 12px; color: var(--text-dim); }}
        </style>
    </head>
    <body>
        <div class="header">
            <h1>AI 交易审计报告</h1>
            <p>生成的日期: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | 引擎版本: v1.0.16-trial</p>
        </div>
        
        {"".join([f'''
        <div class="audit-card">
            <div class="meta">
                <span>TS: {item['ts']}</span>
                <span>ACTION: {item['side']}</span>
            </div>
            <div class="pnl-badge {item['pnl_class']}">
                {"+" if item['pnl'] > 0 else ""}{item['pnl']:.2f} USD
            </div>
            <div class="review">
                <strong>AI 复盘建议：</strong><br/>
                {item['review']}
            </div>
            <div class="evidence-tags">
                {" ".join([f'<span class="tag">{e}</span>' for e in item['evidence']])}
            </div>
        </div>
        ''' for item in audit_items])}

        <div class="footer">
            &copy; 2026 Gold AutoTrade. 本报告由大模型自动生成，仅供技术复盘参考，不构成投资建议。
        </div>
    </body>
    </html>
    """
    
    report_path = reports_dir / "daily_audit.html"
    report_path.write_text(html_template, encoding='utf-8')
    print(f"报告已成功生成: {report_path}")

if __name__ == "__main__":
    generate_audit_report()
