#!/usr/bin/env python3
"""
Download ALL 2025 BTC/EUR data from Binance
Free API, no keys needed
1-minute candles
"""

import requests
import time
import csv
from datetime import datetime

PAIR = 'BTCEUR'
OUTPUT = '/var/www/html/bestrading.cuttalo.com/scripts/prices_BTC_EUR_2025_full.csv'

# Jan 1, 2025 00:00:00 UTC
START_TS = 1735689600000  # milliseconds
# Jan 21, 2026 (now)
END_TS = int(time.time() * 1000)

def download():
    print(f"🚀 Downloading {PAIR} from Binance")
    print(f"📅 From: {datetime.fromtimestamp(START_TS/1000)}")
    print(f"📅 To:   {datetime.fromtimestamp(END_TS/1000)}")

    all_candles = []
    start_time = START_TS
    iteration = 0

    while start_time < END_TS:
        iteration += 1
        url = f"https://api.binance.com/api/v3/klines"
        params = {
            'symbol': PAIR,
            'interval': '1m',
            'startTime': start_time,
            'limit': 1000  # Max per request
        }

        try:
            resp = requests.get(url, params=params, timeout=30)

            if resp.status_code == 429:
                print("⏳ Rate limited, waiting...")
                time.sleep(60)
                continue

            if resp.status_code != 200:
                print(f"❌ Error {resp.status_code}: {resp.text}")
                time.sleep(5)
                continue

            candles = resp.json()

            if not candles:
                print("✅ No more data")
                break

            all_candles.extend(candles)
            start_time = candles[-1][0] + 60000  # Next minute

            if iteration % 50 == 0:
                last_ts = candles[-1][0]
                print(f"   Iter {iteration}: {len(all_candles):,} candles, last: {datetime.fromtimestamp(last_ts/1000)}")

            time.sleep(0.2)  # Rate limit

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

    print(f"\n📊 Total candles: {len(all_candles):,}")

    # Write CSV (OHLCV format)
    print(f"💾 Saving to {OUTPUT}...")
    with open(OUTPUT, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_volume', 'trades', 'taker_buy_base', 'taker_buy_quote', 'ignore'])

        for c in all_candles:
            writer.writerow([
                int(c[0] / 1000),  # Convert to seconds
                c[1], c[2], c[3], c[4], c[5],
                int(c[6] / 1000), c[7], c[8], c[9], c[10], c[11]
            ])

    # Also create simple training format
    training_output = OUTPUT.replace('_full.csv', '_training.csv')
    print(f"💾 Creating training format: {training_output}")
    with open(training_output, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['timestamp', 'price'])
        for c in all_candles:
            writer.writerow([int(c[0] / 1000), c[4]])  # timestamp, close

    print(f"\n✅ Done!")
    print(f"   Full data: {OUTPUT}")
    print(f"   Training:  {training_output}")
    print(f"   Candles:   {len(all_candles):,}")
    if all_candles:
        print(f"   From: {datetime.fromtimestamp(all_candles[0][0]/1000)}")
        print(f"   To:   {datetime.fromtimestamp(all_candles[-1][0]/1000)}")

if __name__ == '__main__':
    download()
