#!/usr/bin/env python3
"""批量再生所有持仓+自选策略，结合技术面支撑/压力位"""

import json
import sys
sys.path.insert(0, '/home/hmo/web-dashboard')

from technical_analysis import full_analysis
from strategy_lifecycle import reassess_strategy

PF = '/home/hmo/web-dashboard/data/portfolio.json'
WL = '/home/hmo/web-dashboard/data/watchlist.json'

def main():
    # 持仓
    pf = json.load(open(PF))
    for s in pf['holdings']:
        code = s['code']
        name = s['name']
        price = s.get('price', 0)
        cost = s.get('cost', 0)
        shares = s.get('shares', 0)
        
        if not price:
            continue
            
        print(f"  {name}({code}) 现价{price} 成本{cost}...", end=' ')
        
        try:
            tech = full_analysis(code)
        except:
            tech = None
            
        result = reassess_strategy(
            code, name, price, cost, shares,
            current_action=s.get('analysis', {}).get('action', '')
        )
        
        if 'analysis' not in s:
            s['analysis'] = {}
        s['analysis']['stop_loss'] = result['stop_loss']
        s['analysis']['take_profit'] = result['take_profit']
        s['analysis']['entry_low'] = result['entry_low']
        s['analysis']['entry_high'] = result['entry_high']
        s['analysis']['action'] = result['action']
        s['analysis']['status'] = result['status']
        s['analysis']['reassessed_at'] = result['reassessed_at']
        
        print(f"损{result['stop_loss']} 盈{result['take_profit']} 区{result['entry_low']}~{result['entry_high']}")
    
    json.dump(pf, open(PF, 'w'), ensure_ascii=False, indent=2)
    print(f"\n持仓策略已更新: {len(pf['holdings'])} 条")
    
    # 自选股 - 简单重新计算买入区
    wl = json.load(open(WL))
    updated = 0
    for s in wl['stocks']:
        code = s['code']
        price = s.get('price', 0)
        if not price:
            continue
        tech = None
        try:
            tech = full_analysis(code)
        except:
            pass
            
        # 买入区 = 弱支撑~弱压力
        if tech:
            sr = tech.get('support_resistance', {})
            ws = sr.get('weak_support') or price * 0.95
            wr = sr.get('weak_resist') or price * 1.05
        else:
            ws = price * 0.92
            wr = price * 1.08
            
        if 'analysis' not in s:
            s['analysis'] = {}
        s['analysis']['buy_low'] = round(ws, 2)
        s['analysis']['buy_high'] = round(wr, 2)
        if tech:
            s['analysis']['tech_levels'] = {
                'strong_support': sr.get('strong_support'),
                'weak_support': sr.get('weak_support'),
                'weak_resist': sr.get('weak_resist'),
                'strong_resist': sr.get('strong_resist'),
            }
        updated += 1
        print(f"  {s['name']}({code}) 买入区={ws:.2f}~{wr:.2f}")
    
    json.dump(wl, open(WL, 'w'), ensure_ascii=False, indent=2)
    print(f"\n自选策略已更新: {updated} 条")
    print("\n✅ 全部策略再生完成")

if __name__ == '__main__':
    main()
