#!/usr/bin/env python3
"""
Download Bitcoin 2024 historical data from Binance.
"""

import requests
import pandas as pd
from datetime import datetime, timedelta
import time

BINANCE_API = 'https://api.binance.com/api/v3'
OUTPUT_FILE = '/var/www/html/pippo.cuttalo.com/data/prices_BTC_EUR_2024.csv'


def download_klines(symbol, interval, start_date, end_date):
    """Download klines from Binance."""
    all_data = []
    current = start_date

    print(f"Downloading {symbol} {interval} data from {start_date} to {end_date}")

    while current < end_date:
        params = {
            'symbol': symbol,
            'interval': interval,
            'startTime': int(current.timestamp() * 1000),
            'limit': 1000
        }

        try:
            resp = requests.get(f'{BINANCE_API}/klines', params=params, timeout=10)
            data = resp.json()

            if not data:
                break

            for k in data:
                all_data.append({
                    'timestamp': datetime.fromtimestamp(k[0] / 1000),
                    'open': float(k[1]),
                    'high': float(k[2]),
                    'low': float(k[3]),
                    'close': float(k[4]),
                    'volume': float(k[5])
                })

            current = datetime.fromtimestamp(data[-1][0] / 1000) + timedelta(minutes=1)
            print(f"Downloaded up to {current.strftime('%Y-%m-%d %H:%M')}, total: {len(all_data)} candles")

            time.sleep(0.1)  # Rate limiting

        except Exception as e:
            print(f"Error: {e}")
            time.sleep(5)

    return all_data


if __name__ == '__main__':
    # Download 2024 data
    data = download_klines(
        'BTCEUR',
        '1m',
        datetime(2024, 1, 1),
        datetime(2025, 1, 1)
    )

    if data:
        df = pd.DataFrame(data)
        df.to_csv(OUTPUT_FILE, index=False)
        print(f"\nSaved {len(df)} candles to {OUTPUT_FILE}")
    else:
        print("No data downloaded")
