#!/usr/bin/env python3
"""每周交易报告（目标门禁版）."""
import sys
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).parent.parent
SRC_DIR = ROOT / "src"
for candidate in (ROOT, SRC_DIR):
    candidate_str = str(candidate)
    if candidate_str not in sys.path:
        sys.path.insert(0, candidate_str)

from metrics_agg import aggregate_goal_targets  # type: ignore


def build_weekly_payload() -> dict:
    target = aggregate_goal_targets(ROOT, "default")
    week = target.get("window_week", {}) if isinstance(target.get("window_week", {}), dict) else {}
    month = target.get("window_month", {}) if isinstance(target.get("window_month", {}), dict) else {}
    gates = target.get("gates", {}) if isinstance(target.get("gates", {}), dict) else {}
    return {
        "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M"),
        "window_week": week,
        "window_month": month,
        "gates": gates,
    }


def format_feishu_message(data: dict) -> str:
    week = data.get("window_week", {}) if isinstance(data.get("window_week", {}), dict) else {}
    month = data.get("window_month", {}) if isinstance(data.get("window_month", {}), dict) else {}
    gates = data.get("gates", {}) if isinstance(data.get("gates", {}), dict) else {}
    status = "PASS" if bool(gates.get("all_passed", False)) else "WATCH"

    return f"""[STATS] 黄金自动交易 - 每周摘要

[UP] 本周汇总
• 周已实现盈亏: ${float(week.get('realized_pnl', 0.0) or 0.0):+.2f}
• 周平仓笔数: {int(week.get('closed_trade_count', week.get('closed_trades', 0)) or 0)}
• 周胜率: {float(week.get('win_rate_pct', 0.0) or 0.0):.1f}%
• 周盈亏比(PF): {float(week.get('profit_factor', 0.0) or 0.0):.2f}
• 周最大回撤: {float(week.get('max_drawdown_pct', 0.0) or 0.0):.2f}%
• 周最大连亏: {int(week.get('consecutive_loss_max', 0) or 0)}

[HIT] 终态门禁(月口径)
• 状态: {status}
• 月回撤: {float(month.get('max_drawdown_pct', 0.0) or 0.0):.2f}% / 阈值<= {float((gates.get('max_drawdown_pct', {}) or {}).get('threshold', 10.0) or 10.0):.2f}%
• 月自治率: {float(month.get('autonomy_rate_pct', 0.0) or 0.0):.2f}% / 阈值>= {float((gates.get('autonomy_rate_pct', {}) or {}).get('threshold', 85.0) or 85.0):.2f}%
• 月人工干预交易日: {int(month.get('manual_trade_days_count', 0) or 0)}
• 月自主交易日: {int(month.get('autonomous_trade_days_count', 0) or 0)}

[CLOCK] 报告时间: {data.get('generated_at', '')}"""


if __name__ == "__main__":
    print(format_feishu_message(build_weekly_payload()))
