#!/usr/bin/env python3
import json
import subprocess
import sys
import os
from datetime import datetime

# 读取持仓数据
with open('data/portfolio.json', 'r') as f:
    portfolio = json.load(f)

# 读取决策数据
with open('data/decisions.json', 'r') as f:
    decisions_data = json.load(f)

# 获取所有持仓股票
holdings = portfolio['holdings']
active_holdings = [h for h in holdings if h.get('shares', 0) > 0]

print(f"持仓股票数量: {len(active_holdings)}")

# 获取实时价格 - 使用curl调用API
# 注意：这里需要根据实际情况调整API调用
realtime_prices = {}

for holding in active_holdings:
    code = holding['code']
    name = holding['name']
    
    # 判断市场类型
    # 港股代码5位数字（如01211），优先判断
    if len(code) == 5:  # 港股
        market = 'hk'
        price = holding['price']
        change_pct = holding.get('change_pct', 0)
        realtime_prices[code] = {
            'name': name,
            'price': price,
            'change_pct': change_pct,
            'market': 'HK'
        }
    elif code.startswith('6'):  # 沪市
        market = 'sh'
        price = holding['price']
        change_pct = holding.get('change_pct', 0)
        realtime_prices[code] = {
            'name': name,
            'price': price,
            'change_pct': change_pct,
            'market': 'A'
        }
    elif code.startswith('0') or code.startswith('3'):  # 深市
        market = 'sz'
        price = holding['price']
        change_pct = holding.get('change_pct', 0)
        realtime_prices[code] = {
            'name': name,
            'price': price,
            'change_pct': change_pct,
            'market': 'A'
        }
    else:
        # 其他类型
        price = holding['price']
        change_pct = holding.get('change_pct', 0)
        realtime_prices[code] = {
            'name': name,
            'price': price,
            'change_pct': change_pct,
            'market': 'OTHER'
        }

# 获取活跃决策
active_decisions = [d for d in decisions_data['decisions'] if d.get('status') == 'active']

print(f"活跃决策数量: {len(active_decisions)}")

# 输出结果
print("\n=== 实时价格数据 ===")
for code, data in realtime_prices.items():
    print(f"{code} {data['name']}: {data['price']} ({data['change_pct']:+.2f}%)")

# 保存到临时文件供后续使用
output_data = {
    'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    'prices': realtime_prices,
    'holdings': active_holdings,
    'active_decisions': active_decisions
}

with open('data/temp_realtime.json', 'w') as f:
    json.dump(output_data, f, indent=2, ensure_ascii=False)

print(f"\n数据已保存到 data/temp_realtime.json")