<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../../engine/api-handling/api_helpers.php';
require_once __DIR__ . '/../../engine/api-handling/fred_fetch.php';

/**
 * Erwartete Helper:
 * - fetch_fred_series($seriesId, $startIso='1980-01-01') -> ['date'=>'YYYY-MM-DD','value'=>float|null][]
 * - month_end($Y,$m) o.ä. nicht zwingend; wir mappen auf "YYYY-MM"
 */

function to_month_map($rows) {
  $out = [];
  foreach ($rows as $r) {
	if (!isset($r['date']) || $r['value']==='' || $r['value']===null) continue;
	$ym = substr($r['date'],0,7); // YYYY-MM
	$v = floatval($r['value']);
	$out[$ym] = $v; // last value in month wins
  }
  krsort($out); $out = array_reverse($out, true);
  return $out;
}

function yoy_percent($series) {
  // $series: map YYYY-MM => value
  $keys = array_keys($series);
  $out  = [];
  for ($i=0; $i<count($keys); $i++) {
	$k = $keys[$i];
	$prevIdx = array_search(date('Y-m', strtotime($k.'-01 -12 months')), $keys);
	if ($prevIdx===false) { $out[$k] = null; continue; }
	$kprev = $keys[$prevIdx];
	$a = $series[$kprev]; $b = $series[$k];
	if ($a==0 || $a===null || $b===null) { $out[$k]=null; continue; }
	$out[$k] = ($b/$a - 1.0) * 100.0;
  }
  return $out;
}

function yoy_delta_pp($series) {
  // für Renditen in Prozentpunkten YoY (DGS10)
  $keys = array_keys($series);
  $out  = [];
  for ($i=0; $i<count($keys); $i++) {
	$k = $keys[$i];
	$prevIdx = array_search(date('Y-m', strtotime($k.'-01 -12 months')), $keys);
	if ($prevIdx===false) { $out[$k] = null; continue; }
	$kprev = $keys[$prevIdx];
	$a = $series[$kprev]; $b = $series[$k];
	if ($a===null || $b===null) { $out[$k]=null; continue; }
	$out[$k] = $b - $a; // Prozentpunkte
  }
  return $out;
}

function clamp($x,$lo,$hi){ return max($lo, min($hi, $x)); }

try {
  $usd = to_month_map(fetch_fred_series('DTWEXBGS'));   // Broad Dollar Index
  $oil = to_month_map(fetch_fred_series('DCOILWTICO')); // WTI Spot
  $y10 = to_month_map(fetch_fred_series('DGS10'));      // 10y Yield

  $usd_yoy = yoy_percent($usd);
  $oil_yoy = yoy_percent($oil);
  $y10_pp  = yoy_delta_pp($y10);

  // Komponenten-Score: „fallend = gut“ -> Vorzeichen invertieren und skalieren
  // Skalen: USD & Öl: ±20% bzw. ±50%; 10Y: ±2pp
  $labels = array_values(array_unique(array_merge(array_keys($usd_yoy), array_keys($oil_yoy), array_keys($y10_pp))));
  sort($labels);

  $comp = []; $usd_s=[]; $oil_s=[]; $y10_s=[];
  foreach ($labels as $m) {
	$u = $usd_yoy[$m] ?? null;
	$o = $oil_yoy[$m] ?? null;
	$y = $y10_pp[$m]  ?? null;

	$su = $u===null ? null : ( clamp(-$u, -20, 20) / 20.0 * 100.0 );
	$so = $o===null ? null : ( clamp(-$o, -50, 50) / 50.0 * 100.0 );
	$sy = $y===null ? null : ( clamp(-$y, -2,  2)  / 2.0  * 100.0 );

	$usd_s[] = $su; $oil_s[] = $so; $y10_s[] = $sy;
	$vals = array_values(array_filter([$su,$so,$sy], fn($v)=>$v!==null));
	$comp[] = count($vals) ? round(array_sum($vals)/count($vals), 1) : null;
  }

  // +9 Monate verschoben (Impact)
  $impact = array_fill(0, count($comp), null);
  for ($i=0; $i<count($comp); $i++) {
	$j = $i + 9;
	if ($j < count($comp)) $impact[$j] = $comp[$i];
  }

  // Antwort
  echo json_encode([
	'labels' => $labels,                // YYYY-MM
	'comp'   => $comp,                  // aktueller Macro-Pressure (höher = günstiger)
	'impact' => $impact,                // um +9M verschoben
	'usd'    => $usd_s,
	'oil'    => $oil_s,
	'y10'    => $y10_s
  ]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['error' => $e->getMessage()]);
}