"""Diagnose: check HK stock costs, prices, total assets calculation"""
import sys
sys.path.insert(0, '/home/hmo/MoFin')
from mo_models import calc_total_assets, calc_total_mv, is_hk_stock, to_cny, get_hk_rate
from mo_data import read_portfolio
import json

pf = read_portfolio()
holdings = pf.get('holdings', [])
rate = get_hk_rate()

print(f"HK_RATE: {rate}")
print(f"total_assets (from DB): {pf.get('total_assets')}")
print(f"total_mv (from DB): {pf.get('total_mv')}")
print(f"cash: {pf.get('cash')}")
print(f"frozen_cash: {pf.get('frozen_cash')}")
print(f"position_pct: {pf.get('position_pct')}")

total_mv_calc = calc_total_mv(holdings)
total_assets_calc = calc_total_assets(pf)
print(f"\ncalc_total_mv: {total_mv_calc}")
print(f"calc_total_assets: {total_assets_calc}")

print(f"\n=== HK stocks ===")
for h in holdings:
    code = h.get('code', '')
    if is_hk_stock(str(code)):
        cost = h.get('cost', 0) or 0
        price = h.get('price', 0) or 0
        shares = h.get('shares', 0) or 0
        mv = price * shares
        cost_calc = cost * shares
        pnl = (price - cost) * shares if cost > 0 else 0
        pnl_pct = (price - cost) / cost * 100 if cost > 0 else 0
        print(f"  {code} {h.get('name')}: cost={cost} price={price} shares={shares} mv={mv} pnl={pnl:.1f} ({pnl_pct:+.1f}%)")
