"""Helpers for loading the latest trading simulation snapshot from the database."""
from typing import Any, Dict

from sqlalchemy.orm import Session

from app.api.trading_persistent import get_or_create_simulation, get_portfolio_state_from_db


def load_simulation_state(db: Session, user_id: str = "default") -> Dict[str, Any]:
    """Return the current simulation state as a serializable dict."""
    try:
        simulation = get_or_create_simulation(db, user_id)
        portfolio = get_portfolio_state_from_db(simulation, db)
        return portfolio.dict()
    except Exception as e:
        # If database tables don't exist, return default state
        print(f"Warning: Could not load simulation state: {e}")
        return {
            "cash": 100000.0,
            "position": None,
            "trades": [],
            "total_pnl": 0.0,
            "win_rate": 0.0,
            "avg_win": 0.0,
            "avg_loss": 0.0,
            "trade_count": 0
        }
