"""Fix: HK stock currency=CYN, recalc portfolio_summary"""
import sqlite3, sys
sys.path.insert(0, '/home/hmo/MoFin')
from mo_models import is_hk_stock
from datetime import datetime

db = sqlite3.connect('/home/hmo/web-dashboard/data/mofin.db')

# 1. Fix all HK stock currency to CNY
fixed = 0
for r in db.execute("SELECT code, name, cost, price, shares, currency FROM holdings WHERE is_active=1"):
    code, name, cost, price, shares, curr = r
    if is_hk_stock(str(code)):
        db.execute("UPDATE holdings SET currency='CNY' WHERE code=?", (code,))
        print(f"  FIXED HK currency: {code} {name}: {curr} -> CNY")
        fixed += 1
print(f"Fixed {fixed} HK stock currencies\n")

# 2. Recalc portfolio_summary
rows = db.execute("SELECT code, shares, cost, price FROM holdings WHERE is_active=1").fetchall()
total_mv = sum((r[3] or 0) * (r[1] or 0) for r in rows)
total_cost = sum((r[2] or 0) * (r[1] or 0) for r in rows)
total_pnl = total_mv - total_cost

sr = db.execute("SELECT cash, frozen_cash FROM portfolio_summary WHERE id=1").fetchone()
cash = sr[0] or 0
frozen = sr[1] or 0
total_assets = total_mv + cash + frozen
position_pct = round(total_mv / total_assets * 100, 2) if total_assets > 0 else 0

db.execute("UPDATE portfolio_summary SET total_mv=?, total_assets=?, total_pnl=?, position_pct=?, updated_at=? WHERE id=1",
           (round(total_mv,2), round(total_assets,2), round(total_pnl,2), position_pct, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
print(f"portfolio_summary: mv={total_mv:.2f} ta={total_assets:.2f} pnl={total_pnl:.2f} pos={position_pct}%")

# 3. Check 00700 cost
r = db.execute("SELECT cost FROM holdings WHERE code='00700'").fetchone()
if r and (r[0] is None or r[0] == 0):
    print("\n⚠️ 00700 腾讯 cost=0 — 需要从 holding.xls 重新导入")

db.commit()
db.close()
print("\nDone.")
