================================================================================
                        FinSim — HOW TO RUN (Complete Guide)
================================================================================

Last Updated: March 31, 2026


================================================================================
  WHAT WAS INSTALLED ON YOUR MACHINE
================================================================================

  1. UV Package Manager (v0.11.2)
     - Location: C:\Users\fmfmf\.local\bin\uv.exe
     - UV is a modern Python package manager (replaces pip/venv/virtualenv)

  2. Python 3.12.13 (installed via UV)
     - Managed by UV, no need to install separately

  3. Virtual Environment + 67 Python packages
     - Location: investment_engine\.venv\
     - All dependencies (FastAPI, Polars, yfinance, LangChain, Groq, etc.)

  4. LangGraph was added as a missing dependency to pyproject.toml


================================================================================
  QUICK START — Run FinSim
================================================================================

  Open PowerShell (or Windows Terminal) and run:

    cd C:\Users\fmfmf\Desktop\FinSim\FinSim\investment_engine
    $env:Path = "C:\Users\fmfmf\.local\bin;$env:Path"
    uv run python main.py

  Then open your browser to:

    http://localhost:8000

  That's it! The UI has two panels:
    - LEFT:  "Generate Historical Scenarios" — fetches stock data, runs AI, saves to DB
    - RIGHT: "Interactive Advisor Bot" — chat with the AI investment advisor


================================================================================
  STOPPING THE SERVER
================================================================================

  Press Ctrl+C in the terminal where the server is running.


================================================================================
  DETAILED STEP-BY-STEP (First Time Setup)
================================================================================

  If you ever need to set this up on a fresh machine again:

  Step 1: Install UV (one-time)
  ────────────────────────────
    Open Powershell and run:
      Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
      irm https://astral.sh/uv/install.ps1 | iex

  Step 2: Add UV to PATH (every new terminal session)
  ────────────────────────────────────────────────────
      $env:Path = "C:\Users\fmfmf\.local\bin;$env:Path"

    TIP: To make this permanent, add C:\Users\fmfmf\.local\bin to your
    Windows System PATH via:
      Settings > System > About > Advanced system settings >
      Environment Variables > Path > Edit > New

  Step 3: Install Python (one-time)
  ─────────────────────────────────
      uv python install 3.12

  Step 4: Navigate to project and sync dependencies
  ──────────────────────────────────────────────────
      cd C:\Users\fmfmf\Desktop\FinSim\FinSim\investment_engine
      uv sync

  Step 5: Run the application
  ───────────────────────────
      uv run python main.py


================================================================================
  DATABASE INFO (Already Connected & Working)
================================================================================

  Host:     scenariodb.caprover.al-arcade.com
  Port:     3306
  User:     root
  Password: Alarcade123#
  Database: mcq_app
  Table:    scenarios (141 scenarios currently in DB)

  Other tables in the DB: quiz_attempts, quiz_scenarios, quizzes,
                          user_scenario_history, users

  The database connection is configured in:
    investment_engine\config.py  (default values)

  Connection is tested automatically on app startup (init_db).


================================================================================
  API KEYS (Already Configured in .env)
================================================================================

  File: investment_engine\.env

  Contains:
    GROQ_API_KEY     — For the Llama-3.3-70b AI (scenario generation + chat)
    SERPAPI_API_KEY   — For real-time web search in the chat bot

  If keys expire, replace them in the .env file. No code changes needed.


================================================================================
  API ENDPOINTS
================================================================================

  GET  /          → Serves the Web UI (index.html)
  POST /generate  → Generates scenarios (body: JSON with stock_symbol, etc.)
  POST /chat      → Chat with the advisor bot (body: JSON with message)

  Example curl for generate:
    curl -X POST http://localhost:8000/generate ^
      -H "Content-Type: application/json" ^
      -d "{\"stock_symbol\":\"AAPL\",\"zscore_window\":100,\"zscore_trigger_min\":-2.5,\"zscore_trigger_max\":2.5}"

  Example curl for chat:
    curl -X POST http://localhost:8000/chat ^
      -H "Content-Type: application/json" ^
      -d "{\"session_id\":\"my_session\",\"message\":\"Give me a scenario\"}"


================================================================================
  PROJECT FILE STRUCTURE
================================================================================

  investment_engine\
  ├── main.py                  Entry point (starts Uvicorn server on port 8000)
  ├── app.py                   FastAPI app with /generate and /chat routes
  ├── config.py                Environment config (DB creds, API keys, defaults)
  ├── models.py                Pydantic data models (request/response contracts)
  ├── .env                     Secret keys (GROQ_API_KEY, SERPAPI_API_KEY)
  ├── pyproject.toml           Project definition + dependencies
  ├── uv.lock                  Locked dependency versions
  ├── services\
  │   ├── zscore_engine.py     Polars Z-Score calculation + yfinance data fetch
  │   ├── scenario_gen.py      Groq LLM prompt → structured MCQ generation
  │   ├── database.py          MySQL connection pool, insert, random fetch
  │   └── chat_agent.py        LangGraph ReAct agent (advisor bot)
  └── static\
      └── index.html           Frontend UI (dark theme, two-panel layout)


================================================================================
  TROUBLESHOOTING
================================================================================

  Problem: "uv is not recognized"
  Solution: Run this first in your terminal:
    $env:Path = "C:\Users\fmfmf\.local\bin;$env:Path"

  Problem: "Python was not found"
  Solution: Don't run "python" directly. Always use "uv run python ..."
    UV manages its own Python installation.

  Problem: "GROQ_API_KEY is not set"
  Solution: Make sure the .env file exists in the investment_engine folder
    and contains your key: GROQ_API_KEY=gsk_...

  Problem: "Could not initialize DB on startup"
  Solution: Check your internet connection. The MySQL database is remote
    (hosted on CapRover). If the host is down, the app will still start
    but DB features won't work.

  Problem: Port 8000 already in use
  Solution: Either stop the other process using port 8000, or edit main.py
    and change the port number in: uvicorn.run("app:app", port=8000)

  Problem: "No events found for any requested symbols"
  Solution: yfinance may have rate-limited you. Wait a minute and try again,
    or try a different stock symbol.

  Problem: Generation takes too long
  Solution: The scenario generation pipeline does 3 things sequentially:
    1. Downloads 5 years of stock data (yfinance) — ~5 seconds
    2. Calculates Z-Scores with Polars — instant
    3. Calls Groq LLM to generate scenarios — ~10-20 seconds
    Total: ~15-30 seconds is normal.


================================================================================
  USEFUL COMMANDS
================================================================================

  Start the server:
    uv run python main.py

  Add a new dependency:
    uv add <package-name>

  Update all dependencies:
    uv sync --upgrade

  Run a one-off Python script:
    uv run python <script.py>

  Check installed packages:
    uv pip list


================================================================================
