<?php
require_once __DIR__ . '/fmp_registry.php';
require_once __DIR__ . '/api_helpers.php';
require_once __DIR__ . '/api_helpers_multi_fetch.php';

/**
 * Universeller Multi-Fetch über Registry.
 * Nutzt fetch_multi_safe(), wenn vorhanden – sonst fallback auf fetch_multi().
 */
function fmp_multi(array $requests, int $timeout = 10): array {
    $urls = [];
    foreach ($requests as $alias => $r) {
        $urls[$alias] = fmp_build_url($r['key'] ?? '', $r['vars'] ?? [], $r['query'] ?? []);
    }

    if (function_exists('fetch_multi_safe')) {
        return fetch_multi_safe($urls, $timeout, 1, 600);
    }
    return fetch_multi($urls, $timeout);
}

/**
 * Mehrere Symbole × mehrere Keys in einem Rutsch.
 */
function fmp_multi_for_symbols(array $keys, array $symbols, array $commonQuery = [], int $timeout = 10): array {
    $symbols = array_values(array_unique(array_filter($symbols)));
    $requests = [];
    foreach ($symbols as $sym) {
        foreach ($keys as $k) {
            $q = $commonQuery;
            if ($k === 'income_statement' && !isset($q['limit'])) $q['limit'] = 4;
            $requests["{$sym}.{$k}"] = ['key' => $k, 'vars' => ['symbol' => $sym], 'query' => $q];
        }
    }
    $raw = fmp_multi($requests, $timeout);

    $out = [];
    foreach ($symbols as $sym) {
        $out[$sym] = [];
        foreach ($keys as $k) {
            $alias = "{$sym}.{$k}";
            $data  = $raw[$alias] ?? [];
            if ($k === 'profile')         $data = is_array($data) ? ($data[0] ?? []) : [];
            if ($k === 'key_metrics_ttm') $data = is_array($data) ? ($data[0] ?? []) : [];
            $out[$sym][$k] = $data;
        }
    }
    return $out;
}
