import sys
import json
import yfinance as yf


def get_stock_data(tickers, period='1y'):
    results = {}
    for ticker in tickers:
        ticker = ticker.strip().upper()
        if not ticker:
            continue
        try:
            stock = yf.Ticker(ticker)
            # Single call: 1 year of daily bars. Gives us current price, previous
            # close, 52-week high/low, AND the full series for chart period
            # toggling (7d/30d/6mo/1y) -- all without extra requests per ticker,
            # which is what was tripping the earlier 404/rate-limit errors.
            hist = stock.history(period=period, interval='1d')

            if hist.empty:
                results[ticker] = {
                    "status": "error",
                    "message": f"{ticker}: no historical data returned by source."
                }
                continue

            closes = hist['Close']
            highs = hist['High']
            lows = hist['Low']
            dates = hist.index

            current_price = float(closes.iloc[-1])
            previous_close = float(closes.iloc[-2]) if len(closes) > 1 else current_price
            change = current_price - previous_close
            pct_change = (change / previous_close * 100) if previous_close else 0.0

            fifty_two_week_high = float(highs.max())
            fifty_two_week_low = float(lows.min())

            all_dates = [d.strftime('%Y-%m-%d') for d in dates]
            all_prices = [round(float(p), 2) for p in closes]

            # FIX: timestamp of the actual last data row from the source,
            # not the moment this script was invoked.
            quote_date = dates[-1].strftime('%Y-%m-%d')

            results[ticker] = {
                "status": "success",
                "price": round(current_price, 2),
                "price_display": f"${current_price:.2f}",
                "previous_close": round(previous_close, 2),
                "change": round(change, 2),
                "change_pct": round(pct_change, 2),
                "fifty_two_week_high": round(fifty_two_week_high, 2),
                "fifty_two_week_low": round(fifty_two_week_low, 2),
                "quote_date": quote_date,
                "history_dates": all_dates,
                "history_prices": all_prices
            }
        except Exception as e:
            results[ticker] = {"status": "error", "message": f"{ticker}: {str(e)}"}
    return results


if __name__ == "__main__":
    if len(sys.argv) > 1:
        input_tickers = sys.argv[1].split(',')
        requested_period = sys.argv[2] if len(sys.argv) > 2 else '1y'
        print(json.dumps(get_stock_data(input_tickers, requested_period)))
    else:
        print(json.dumps({"error": "No tickers provided"}))
