#!/usr/bin/env python3
"""一次性修复：将 holdings 表中港股成本从 HKD 转为 CNY。
运行时机：import_holding_xls.py 修复后，旧数据需要转换。
"""
import sqlite3, sys, os

sys.path.insert(0, '/home/hmo/MoFin')
from mo_models import is_hk_stock
from hk_rate import hkd_to_cny

rate = hkd_to_cny()
DB = '/home/hmo/web-dashboard/data/mofin.db'

print(f"HK_RATE = {rate}")
print(f"DB = {DB}")

db = sqlite3.connect(DB)
rows = db.execute(
    "SELECT code, name, cost, shares, currency FROM holdings WHERE is_active=1"
).fetchall()

fixed = 0
for r in rows:
    code = r[0]
    name = r[1]
    cost = r[2] or 0
    shares = r[3] or 0
    curr = r[4] or 'CNY'

    if not is_hk_stock(str(code)):
        continue
    if cost <= 0:
        continue

    cost_cny = round(cost * rate, 2)
    print(f"  FIX: {code} {name}: cost {cost} -> {cost_cny} CNY (shares={shares})")
    db.execute(
        "UPDATE holdings SET cost=?, currency=? WHERE code=?",
        (cost_cny, 'CNY', code)
    )
    fixed += 1

db.commit()
db.close()

print(f"\nDone. Fixed {fixed} HK stock costs.")
