"""
dry_run_check.py

Run this FIRST after setting up .env, before ever starting monitor.py.
It validates: config.json parses, .env credentials are present and
Alpaca accepts them, account is reachable, and (if run during market
hours) that a basic SIP data pull works. Makes NO trades.

    python dry_run_check.py
"""

import sys
from datetime import datetime, timedelta, timezone

from config_loader import get_config, get_env, validate_config, ConfigValidationError
from logger_setup import get_logger

log = get_logger("dry_run_check")


def main():
    print("=== SIP Bot Dry Run Check ===\n")

    # 1. Config
    try:
        cfg = get_config()
        print(f"[OK] config.json loaded. execution_mode="
              f"{cfg['mode']['execution_mode']}, universe=${cfg['universe']['price_min']}"
              f"-${cfg['universe']['price_max']}")
    except Exception as e:
        print(f"[FAIL] Could not load config.json: {e}")
        sys.exit(1)

    try:
        validate_config(cfg)
        print("[OK] config.json values pass basic sanity checks (positive numbers where required)")
    except ConfigValidationError as e:
        print(f"[FAIL] {e}")
        sys.exit(1)

    # 2. Env / credentials
    try:
        env = get_env()
        env.validate()
        print(f"[OK] .env credentials present. base_url={env.base_url}")
    except Exception as e:
        print(f"[FAIL] {e}")
        sys.exit(1)

    # 3. Alpaca connectivity
    try:
        from alpaca_client import get_client
        client = get_client()
        account = client.get_account()
        print(f"[OK] Connected to Alpaca. account_status={account.status}, "
              f"equity=${account.equity}, buying_power=${account.buying_power}")
    except Exception as e:
        print(f"[FAIL] Could not connect to Alpaca trading API: {e}")
        sys.exit(1)

    # 4. Market data pull
    try:
        now = datetime.now(timezone.utc)
        start = now - timedelta(days=2)
        bars = client.get_minute_bars("AAPL", start, now, limit=5)
        if bars:
            print(f"[OK] Market data pull succeeded ({len(bars)} bars for AAPL)")
        else:
            print("[WARN] Market data pull returned 0 bars (may be normal outside market hours)")
    except Exception as e:
        print(f"[FAIL] Market data pull failed: {e}")
        sys.exit(1)

    # 5. Data directories writable
    try:
        import data_store
        data_store.ensure_dirs()
        print("[OK] Data/state/log directories exist and are writable")
    except Exception as e:
        print(f"[FAIL] Could not create data directories: {e}")
        sys.exit(1)

    print("\n=== All checks passed. Safe to run monitor.py ===")
    if cfg["mode"]["execution_mode"] != "simulation":
        print(f"NOTE: execution_mode is '{cfg['mode']['execution_mode']}' — real orders "
              f"WILL be submitted to your Alpaca account. Set mode.execution_mode to "
              f"'simulation' in config.json if you want to dry-run the full day first.")


if __name__ == "__main__":
    main()
