"""Diagnostic: what does Alpaca actually return for each data feed?

Run from the backend folder:
    .venv\\Scripts\\python.exe diagnose_alpaca.py [SYMBOL]
"""
import os
import sys

import httpx
from dotenv import load_dotenv

load_dotenv()

symbol = sys.argv[1] if len(sys.argv) > 1 else "PLTR"
key = os.getenv("ALPACA_API_KEY", "")
secret = os.getenv("ALPACA_API_SECRET", "")

print(f"Symbol: {symbol}")
print(f"DATA_PROVIDER = {os.getenv('DATA_PROVIDER')}")
print(f"Key loaded: {'yes (' + key[:6] + '...)' if key else 'NO — check backend/.env'}")
print("-" * 60)

for feed in ("sip", "delayed_sip", "iex"):
    try:
        r = httpx.get(
            f"https://data.alpaca.markets/v2/stocks/{symbol}/bars",
            params={"timeframe": "1Day", "limit": 3, "feed": feed, "adjustment": "split"},
            headers={"APCA-API-KEY-ID": key, "APCA-API-SECRET-KEY": secret},
            timeout=15,
        )
        if r.status_code != 200:
            print(f"feed={feed:12s} HTTP {r.status_code}: {r.text[:120]}")
            continue
        bars = r.json().get("bars") or []
        if not bars:
            print(f"feed={feed:12s} HTTP 200 but no bars returned")
            continue
        for b in bars[-3:]:
            print(f"feed={feed:12s} {b['t'][:10]}  open {b['o']:>8}  high {b['h']:>8}  "
                  f"low {b['l']:>8}  close {b['c']:>8}  vol {b['v']:,}")
    except Exception as exc:  # noqa: BLE001
        print(f"feed={feed:12s} ERROR: {exc}")
    print("-" * 60)

print("Compare the 'close' values above against Yahoo Finance for the same dates.")
print("The app prefers: sip -> delayed_sip -> iex (first feed that succeeds).")
