#!/usr/bin/env python3
"""每日交易摘要（目标门禁版）.

用法:
  python3 cron_daily_summary.py
"""
import json
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 _load_promotion_mode() -> str:
    runtime_path = ROOT / "tenants" / "default" / "ops" / "runtime_state.json"
    if not runtime_path.exists():
        return "shadow"
    try:
        payload = json.loads(runtime_path.read_text(encoding="utf-8"))
    except Exception:
        return "shadow"
    return str(payload.get("promotion_mode", "shadow") or "shadow")


def build_daily_payload() -> dict:
    target = aggregate_goal_targets(ROOT, "default")
    day = target.get("window_day", {}) if isinstance(target.get("window_day", {}), 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_day": day,
        "gates": gates,
        "promotion_mode": _load_promotion_mode(),
    }


def format_feishu_message(data: dict) -> str:
    day = data.get("window_day", {}) if isinstance(data.get("window_day", {}), dict) else {}
    gates = data.get("gates", {}) if isinstance(data.get("gates", {}), dict) else {}
    status = "PASS" if bool(gates.get("all_passed", False)) else "WATCH"
    emoji = "[UP]" if float(day.get("realized_pnl", 0.0) or 0.0) >= 0 else "[DOWN]"
    return f"""{emoji} 黄金自动交易 - 每日摘要

[STATS] 交易概览
• 日已实现盈亏: ${float(day.get('realized_pnl', 0.0) or 0.0):+.2f}
• 平仓笔数: {int(day.get('closed_trade_count', day.get('closed_trades', 0)) or 0)}
• 胜率: {float(day.get('win_rate_pct', 0.0) or 0.0):.1f}%
• 盈亏比(PF): {float(day.get('profit_factor', 0.0) or 0.0):.2f}

[HIT] 终态门禁(按月口径判定)
• 状态: {status}
• 回撤门禁: {float((gates.get('max_drawdown_pct', {}) or {}).get('current', 0.0) or 0.0):.2f}% <= {float((gates.get('max_drawdown_pct', {}) or {}).get('threshold', 10.0) or 10.0):.2f}%
• 自治门禁: {float((gates.get('autonomy_rate_pct', {}) or {}).get('current', 0.0) or 0.0):.2f}% >= {float((gates.get('autonomy_rate_pct', {}) or {}).get('threshold', 85.0) or 85.0):.2f}%
• 当前模式: {data.get('promotion_mode', 'shadow')}
• 人工干预标记(当日): {int(day.get('manual_intervention_flag', 0) or 0)}

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


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