<?php

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../services/MarketDataProviderService.php';

function out($msg){ echo '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL; }

function active_symbols()
{
    global $argv;
    if (!empty($argv[1])) return [['symbol' => $argv[1]]];

    return db()->query("SELECT * FROM symbols WHERE is_active = 1 ORDER BY symbol ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

function active_timeframes()
{
    global $argv;
    if (!empty($argv[2])) return [['code' => $argv[2], 'api_interval' => $argv[2]]];

    return db()->query("SELECT * FROM timeframes WHERE is_active = 1 ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

function insert_candle($symbol, $timeframe, $candle)
{
    $openTime = $candle['datetime'] ?? $candle['time'] ?? $candle['timestamp'] ?? $candle['open_time'] ?? null;

    if (is_numeric($openTime)) {
        $openTime = date('Y-m-d H:i:s', (int)$openTime);
    } elseif ($openTime) {
        $openTime = date('Y-m-d H:i:s', strtotime($openTime));
    }

    if (!$openTime) return false;

    $stmt = db()->prepare("
        INSERT INTO candles
            (symbol, timeframe, open_time, open_price, high_price, low_price, close_price, volume, created_at)
        VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ON DUPLICATE KEY UPDATE
            open_price = VALUES(open_price),
            high_price = VALUES(high_price),
            low_price = VALUES(low_price),
            close_price = VALUES(close_price),
            volume = VALUES(volume)
    ");

    return $stmt->execute([
        $symbol,
        $timeframe,
        $openTime,
        (float)($candle['open'] ?? $candle['o'] ?? 0),
        (float)($candle['high'] ?? $candle['h'] ?? 0),
        (float)($candle['low'] ?? $candle['l'] ?? 0),
        (float)($candle['close'] ?? $candle['c'] ?? 0),
        (float)($candle['volume'] ?? $candle['v'] ?? 0),
    ]);
}

$outputSize = !empty($argv[3]) ? (int)$argv[3] : 5000;

foreach (active_symbols() as $symbolRow) {
    $symbol = $symbolRow['symbol'];

    foreach (active_timeframes() as $tf) {
        $timeframe = $tf['code'] ?? $tf['timeframe'] ?? '';
        $interval = $tf['api_interval'] ?? $timeframe;

        out("Fetching {$symbol} {$timeframe} using provider rotation...");

        $result = MarketDataProviderService::fetchCandles($symbol, $timeframe, $interval, $outputSize);

        if (empty($result['success'])) {
            out('FAILED: ' . ($result['error'] ?? 'Unknown error'));
            continue;
        }

        $inserted = 0;
        foreach ($result['candles'] as $candle) {
            if (insert_candle($symbol, $timeframe, $candle)) {
                $inserted++;
            }
        }

        $provider = $result['provider']['provider'] ?? 'unknown';
        out("Done: {$inserted} candles inserted/updated via {$provider}.");

        sleep(1);
    }
}
