from fastapi import FastAPI, HTTPException
import pandas as pd
import os

app = FastAPI()

DATA_DIR = "/app/data/regimes"

def get_asset_path(asset: str):
    return os.path.join(DATA_DIR, f"{asset}_regimes.parquet")


@app.get("/assets")
def list_assets():
    if not os.path.exists(DATA_DIR):
        return {"assets": []}

    files = os.listdir(DATA_DIR)
    assets = [f.replace("_regimes.parquet", "") for f in files if f.endswith("_regimes.parquet")]
    return {"assets": assets}


@app.get("/data/{asset}/chart")
def get_chart_data(asset: str):
    path = get_asset_path(asset)

    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="Asset not found")

    df = pd.read_parquet(path)
    df["date"] = df["date"].astype(str)

    # Используем уже готовую колонку с текстовым названием режима
    if "market_regime_label" in df.columns:
        df["regime_label"] = df["market_regime_label"].str.lower()
    else:
        # fallback на неизвестный режим
        df["regime_label"] = "unknown"

    return df[["date", "close", "regime_label"]].to_dict(orient="records")


@app.get("/regime/{asset}")
def get_current_regime(asset: str):
    path = get_asset_path(asset)

    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="Asset not found")

    df = pd.read_parquet(path)

    if "market_regime_label" not in df.columns:
        raise HTTPException(status_code=400, detail="No regime column")

    latest = df.iloc[-1]
    label = latest["market_regime_label"].lower()

    return {
        "regime_label": label,
        "buy_reasonable": label == "bull",
        "advice": f"Current regime detected as {label}."
    }