import pandas as pd
import pandas_ta as ta
from binance.client import Client
import json
import os

# --- Configuration ---
SYMBOL = "BTCUSDT"
TIMEFRAMES = ["1m", "5m", "15m", "1h", "4h"]
DATA_FILE = "btc_data.jsonl"
LIMIT = 1000  # Number of candles to fetch for each timeframe

# --- Binance Client ---
# In a real application, use environment variables or a secure config file for API keys
api_key = os.environ.get("BINANCE_API_KEY")
api_secret = os.environ.get("BINANCE_API_SECRET")
client = Client(api_key, api_secret)


def fetch_data(symbol, timeframe, limit):
    """Fetches k-line data from Binance."""
    try:
        klines = client.get_historical_klines(symbol, timeframe, f"{limit} hours ago UTC")
        df = pd.DataFrame(
            klines,
            columns=[
                "timestamp",
                "open",
                "high",
                "low",
                "close",
                "volume",
                "close_time",
                "quote_asset_volume",
                "number_of_trades",
                "taker_buy_base_asset_volume",
                "taker_buy_quote_asset_volume",
                "ignore",
            ],
        )
        return df
    except Exception as e:
        print(f"Error fetching data for {symbol} {timeframe}: {e}")
        return None


def calculate_indicators(df):
    """Calculates technical indicators."""
    if df is None or df.empty:
        return None

    # Convert columns to numeric
    for col in ["open", "high", "low", "close", "volume"]:
        df[col] = pd.to_numeric(df[col])

    # Calculate EMAs
    df["ema_20"] = ta.ema(df["close"], length=20)
    df["ema_50"] = ta.ema(df["close"], length=50)
    df["ema_200"] = ta.ema(df["close"], length=200)

    # Calculate VWAP
    df.ta.vwap(append=True)

    # Calculate MACD
    df.ta.macd(append=True)

    # Convert timestamp to datetime
    df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")

    return df


def save_data_to_jsonl(data, filename):
    """Saves a dictionary of dataframes to a JSONL file."""
    with open(filename, "w") as f:
        for timeframe, df in data.items():
            if df is not None:
                df_copy = df.copy()
                df_copy["timestamp"] = df_copy["timestamp"].astype(str)
                records = df_copy.to_dict(orient="records")
                f.write(json.dumps({"timeframe": timeframe, "data": records}) + "\n")


def main():
    """Main function to collect and save data."""
    all_data = {}
    for timeframe in TIMEFRAMES:
        print(f"Fetching data for {SYMBOL} {timeframe}...")
        df = fetch_data(SYMBOL, timeframe, LIMIT)
        if df is not None:
            print(f"Calculating indicators for {timeframe}...")
            df = calculate_indicators(df)
            all_data[timeframe] = df

    print(f"Saving data to {DATA_FILE}...")
    save_data_to_jsonl(all_data, os.path.join("webapp", DATA_FILE))
    print("Data collection complete.")


if __name__ == "__main__":
    main()
