"""Verify total assets and P&L calculation"""
import sqlite3, sys
sys.path.insert(0, '/home/hmo/MoFin')
from mo_models import calc_total_assets, calc_total_mv

db = sqlite3.connect('/home/hmo/web-dashboard/data/mofin.db')
r = db.execute("SELECT * FROM portfolio_summary WHERE id=1").fetchone()
keys = [d[0] for d in db.execute("SELECT * FROM portfolio_summary LIMIT 0").description]
summary = dict(zip(keys, r))

print(f"total_assets (stored): {summary.get('total_assets')}")
print(f"total_mv (stored): {summary.get('total_mv')}")
print(f"total_pnl (stored): {summary.get('total_pnl')}")
print(f"cash: {summary.get('cash')}")
print(f"frozen_cash: {summary.get('frozen_cash')}")

holdings = []
for r in db.execute("SELECT code, name, cost, price, shares FROM holdings WHERE is_active=1"):
    holdings.append({'code': r[0], 'name': r[1], 'cost': r[2] or 0, 'price': r[3] or 0, 'shares': r[4] or 0})

mv = sum(h['price'] * h['shares'] for h in holdings)
total_cost = sum(h['cost'] * h['shares'] for h in holdings)
pnl = mv - total_cost
ta = mv + (summary.get('cash') or 0) + (summary.get('frozen_cash') or 0)

print(f"\nCalculated:")
print(f"total_mv = {mv:.2f}")
print(f"total_cost = {total_cost:.2f}")
print(f"total_pnl = {pnl:.2f}")
print(f"total_assets = {ta:.2f}")

# Check for HK stocks with cost=0 (never converted)
print("\nStocks with cost=0 or None:")
for h in holdings:
    if h['cost'] <= 0 and h['shares'] > 0:
        print(f"  {h['code']} {h['name']}: cost={h['cost']} shares={h['shares']} price={h['price']}")

db.close()
