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

function fetch_fred_series(string $seriesId, string $startIso = '1980-01-01'): array {
	// greift auf global $FredApiKey zurück
	global $FredApiKey;

	if (empty($FredApiKey)) {
		throw new Exception("FRED API key fehlt (global \$FredApiKey).");
	}

	$url = "https://api.stlouisfed.org/fred/series/observations?"
		 . http_build_query([
			 'series_id'    => $seriesId,
			 'api_key'      => $FredApiKey,
			 'file_type'    => 'json',
			 'observation_start' => $startIso
		   ]);

	$ch = curl_init();
	curl_setopt_array($ch, [
		CURLOPT_URL            => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_TIMEOUT        => 15,
	]);
	$res = curl_exec($ch);
	if ($res === false) {
		throw new Exception("FRED fetch error: " . curl_error($ch));
	}
	curl_close($ch);

	$json = json_decode($res, true);
	if (!isset($json['observations'])) {
		throw new Exception("FRED response error for $seriesId");
	}

	$out = [];
	foreach ($json['observations'] as $obs) {
		$val = $obs['value'];
		$out[] = [
			'date'  => $obs['date'],                          // YYYY-MM-DD
			'value' => ($val === '.' ? null : (float)$val)    // null wenn fehlend
		];
	}
	return $out;
}