#!/usr/bin/env python3
"""
重新生成 metrics 数据（带新字段）
"""
import asyncio
import sys
from pathlib import Path

# 添加项目根目录到路径
PROJECT_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from examples.auto_put_ad_mini.tools.roi_calculator import calculate_roi_metrics
from examples.auto_put_ad_mini.tools.portfolio_metrics import calculate_portfolio_summary

# 模拟ToolContext
class SimpleContext:
    """简单的上下文模拟"""
    def __init__(self):
        """初始化空配置字典。"""
        self.config = {}

async def regenerate_data(end_date='20260415'):
    """重新生成metrics和portfolio数据"""
    ctx = SimpleContext()

    print("=" * 70)
    print("  重新生成 Metrics 数据（包含新字段）")
    print("=" * 70)

    # Step 1: 计算 ROI metrics
    print(f"\n📊 步骤 1/2: 计算 ROI metrics (end_date={end_date})")
    try:
        result = await calculate_roi_metrics(ctx, end_date=end_date, min_daily_cost=100.0)
        print(f"✅ {result.title}")
        if result.metadata:
            print(f"   输出文件: {result.metadata.get('metrics_csv')}")
            print(f"   全局ROI均值: {result.metadata.get('动态ROI_7日均值_mean_all', 'N/A')}")
    except Exception as e:
        print(f"❌ ROI计算失败: {e}")
        import traceback
        traceback.print_exc()
        return False

    # Step 2: 计算 portfolio summary
    print(f"\n📊 步骤 2/2: 计算 Portfolio Summary")
    try:
        result = await calculate_portfolio_summary(ctx, end_date=end_date)
        print(f"✅ {result.title}")
        # 打印部分输出
        output_lines = result.output.split('\n')
        for line in output_lines[:20]:
            print(f"   {line}")
    except Exception as e:
        print(f"❌ Portfolio计算失败: {e}")
        import traceback
        traceback.print_exc()
        return False

    print("\n" + "=" * 70)
    print("  ✅ 数据重新生成完成")
    print("=" * 70)
    print("\n提示：现在可以运行 `python3 test_strategy_upgrade.py` 进行验证")

    return True

if __name__ == "__main__":
    end_date = sys.argv[1] if len(sys.argv) > 1 else '20260415'
    success = asyncio.run(regenerate_data(end_date))
    sys.exit(0 if success else 1)
