"""Fix portfolio_summary directly from holdings table"""
import sqlite3, sys
sys.path.insert(0, '/home/hmo/MoFin')
from mo_models import calc_total_mv, calc_total_assets, calc_position_pct
from datetime import datetime

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

# Get holdings
rows = db.execute("SELECT code, name, shares, cost, price, market_value, change_pct, currency, position_pct FROM holdings WHERE is_active=1").fetchall()
holdings = [dict(zip(['code','name','shares','cost','price','market_value','change_pct','currency','position_pct'], r)) for r in rows]

# Get cash/summary
sr = db.execute("SELECT cash, frozen_cash FROM portfolio_summary WHERE id=1").fetchone()
cash = sr[0] or 0
frozen = sr[1] or 0

pf = {'holdings': holdings, 'cash': cash, 'frozen_cash': frozen}
mv = calc_total_mv(holdings)
ta = calc_total_assets(pf)
pp = calc_position_pct(pf)
pnl = sum((h['price'] or 0) * (h['shares'] or 0) - (h['cost'] or 0) * (h['shares'] or 0) for h in holdings)

print(f"mv={mv} ta={ta} pnl={pnl} pp={pp}%")

db.execute("UPDATE portfolio_summary SET total_mv=?, total_assets=?, total_pnl=?, position_pct=?, updated_at=? WHERE id=1",
           (mv, ta, pnl, pp, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
db.commit()
print("portfolio_summary updated")
db.close()
