
import pandas as pd
import yfinance as yf

from jse_tools.core import verify_dataset_integrity


def fetch_market_data(ticker="STXCAP.JO", years=5):

    period = f"{years}y"

    df = yf.download(
        ticker,
        period=period,
        interval="1d",
        auto_adjust=True,
        progress=False
    )

    if df is None or df.empty:
        raise ValueError("Market data download failed")

    # Flatten columns if MultiIndex appears
    if isinstance(df.columns, pd.MultiIndex):
        df.columns = df.columns.get_level_values(0)

    df = df[["Open", "High", "Low", "Close", "Volume"]]

    verify_dataset_integrity(
        df,
        required_columns=["Open", "High", "Low", "Close", "Volume"]
    )

    df.ffill(inplace=True)
    df.bfill(inplace=True)

    return df


def compute_market_regime(df, sma_period=200):

    df["SMA"] = df["Close"].rolling(sma_period).mean()

    latest_close = float(df["Close"].iloc[-1])
    latest_sma = float(df["SMA"].iloc[-1])

    regime = "BULL" if latest_close > latest_sma else "BEAR"

    return {
        "regime": regime,
        "close": latest_close,
        "sma": latest_sma,
        "date": str(df.index[-1])
    }


def get_market_regime(ticker="STXCAP.JO", years=5, sma_period=200):

    df = fetch_market_data(ticker, years)

    return compute_market_regime(df, sma_period)
