from backend.database import init_db, SessionLocal, AccountBalance, Holding, engine
from backend.trader import trader
import logging

logging.basicConfig(level=logging.INFO)

def test_db_migration():
    print("Initializing DB...")
    init_db()
    
    # Check tables
    from sqlalchemy import inspect
    inspector = inspect(engine)
    tables = inspector.get_table_names()
    print(f"Tables: {tables}")
    
    if "account_balance" in tables and "holdings" in tables:
        print("PASS: New tables created.")
    else:
        print("FAIL: Tables missing.")

def test_sync():
    print("Testing Asset Sync (Mocking KIS)...")
    # Note: KIS API might fail if credentials are invalid or market is closed/paper env issues.
    # We will try running it and catch errors.
    try:
        trader.refresh_assets()
        print("Sync function executed.")
        
        db = SessionLocal()
        acc = db.query(AccountBalance).first()
        holdings = db.query(Holding).all()
        
        if acc:
            print(f"Account Balance: Eval={acc.total_eval}, Deposit={acc.deposit}")
        else:
            print("Account Balance: None (Sync might have failed or empty)")
            
        print(f"Holdings Count: {len(holdings)}")
        db.close()
        
    except Exception as e:
        print(f"Sync Logic Error: {e}")

if __name__ == "__main__":
    test_db_migration()
    # test_sync() # Skip actual sync test to avoid making real API calls during verification step unless user wants.
    # Actually user wants "Proceed", so let's try to verify DB schema at least.
