#!/usr/bin/env python3
"""
Download SOL/EUR historical data from Kraken
Nov 1, 2025 - Jan 21, 2026
"""

import requests
import time
import csv
from datetime import datetime

PAIR = 'SOLEUR'
OUTPUT = '/var/www/html/bestrading.cuttalo.com/scripts/prices_SOL_EUR_full.csv'

# Nov 1, 2025 00:00:00 UTC
START_TS = 1730419200
# Jan 21, 2026 (now)
END_TS = int(time.time())

def download():
    print(f"Downloading {PAIR} from {datetime.fromtimestamp(START_TS)} to {datetime.fromtimestamp(END_TS)}")

    all_data = []
    since = START_TS * 1000000000  # Kraken uses nanoseconds

    iteration = 0
    while True:
        iteration += 1
        url = f"https://api.kraken.com/0/public/Trades?pair={PAIR}&since={since}"

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

            if data.get('error') and len(data['error']) > 0:
                print(f"Error: {data['error']}")
                time.sleep(5)
                continue

            result = data.get('result', {})
            trades = result.get(PAIR, [])

            if not trades:
                print("No more trades")
                break

            # Check if we've passed END_TS
            last_ts = float(trades[-1][2])
            if last_ts > END_TS:
                # Filter trades before END_TS
                trades = [t for t in trades if float(t[2]) <= END_TS]
                if trades:
                    all_data.extend(trades)
                print(f"Reached end date. Total: {len(all_data)} trades")
                break

            all_data.extend(trades)
            since = int(result.get('last', since))

            if iteration % 10 == 0:
                print(f"  Iter {iteration}: {len(all_data)} trades, last: {datetime.fromtimestamp(last_ts)}")

            time.sleep(1.1)  # Rate limit

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

    print(f"\nTotal trades: {len(all_data)}")

    # Convert to 1-minute OHLCV
    print("Converting to 1-minute candles...")
    candles = {}

    for trade in all_data:
        price = float(trade[0])
        volume = float(trade[1])
        ts = int(float(trade[2]))
        minute_ts = (ts // 60) * 60

        if minute_ts not in candles:
            candles[minute_ts] = {
                'open': price,
                'high': price,
                'low': price,
                'close': price,
                'volume': volume,
                'count': 1
            }
        else:
            c = candles[minute_ts]
            c['high'] = max(c['high'], price)
            c['low'] = min(c['low'], price)
            c['close'] = price
            c['volume'] += volume
            c['count'] += 1

    # Sort by timestamp
    sorted_ts = sorted(candles.keys())
    print(f"Total candles: {len(sorted_ts)}")

    # Write CSV
    with open(OUTPUT, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['timestamp', 'open', 'high', 'low', 'close', 'vwap', 'volume', 'count'])

        for ts in sorted_ts:
            c = candles[ts]
            vwap = (c['high'] + c['low'] + c['close']) / 3
            writer.writerow([ts, c['open'], c['high'], c['low'], c['close'], vwap, c['volume'], c['count']])

    print(f"Saved to {OUTPUT}")
    print(f"Date range: {datetime.fromtimestamp(sorted_ts[0])} - {datetime.fromtimestamp(sorted_ts[-1])}")

if __name__ == '__main__':
    download()
