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

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

$series = [
    'WALCL'     => 'Fed Balance Sheet',
    'ECBASSETS' => 'ECB Balance Sheet',
];

// Daten holen und auf Monatswerte mappen
$raw = [];
$allMonths = [];

foreach ($series as $id => $label) {
    try {
        $obs = fetch_fred_series($id, '1980-01-01'); // ['date'=>'YYYY-MM-DD','value'=>float|null]
    } catch (Throwable $e) {
        $obs = null;
    }
    if (!$obs) continue;

    foreach ($obs as $row) {
        $val = $row['value'] ?? null;
        if ($val === null || !is_numeric($val)) continue;
        $month = substr($row['date'], 0, 7); // YYYY-MM
        $raw[$id][$month] = (float)$val;     // letzter Wert im Monat gewinnt
        $allMonths[$month] = true;
    }
}

if (empty($raw)) {
    echo json_encode(['error' => 'Keine Daten geladen.']);
    exit;
}

$months = array_keys($allMonths);
sort($months);

// Vorwärts auffüllen je Serie
$aligned = [];
foreach ($series as $id => $label) {
    $prev = null;
    foreach ($months as $m) {
        if (isset($raw[$id][$m])) {
            $prev = $raw[$id][$m];
            $aligned[$id][$m] = $prev;
        } else {
            $aligned[$id][$m] = $prev !== null ? $prev : null;
        }
    }
}

// gemeinsamen gültigen Start suchen
$validStartIndex = 0;
for ($i = 0; $i < count($months); $i++) {
    $ok = true;
    foreach ($series as $id => $label) {
        if (!isset($aligned[$id][$months[$i]]) || $aligned[$id][$months[$i]] === null) { $ok = false; break; }
    }
    if ($ok) { $validStartIndex = $i; break; }
}
if ($validStartIndex > 0) {
    $months = array_slice($months, $validStartIndex);
}

// ln-Werte
$ln = [];
foreach ($series as $id => $label) {
    foreach ($months as $m) {
        $v = $aligned[$id][$m] ?? null;
        $ln[$id][$m] = ($v && $v > 0) ? log($v) : null;
    }
}

// YoY log-diff in %
$chg = [];
for ($i = 12; $i < count($months); $i++) {
    $m  = $months[$i];
    $m12 = $months[$i - 12];
    foreach ($series as $id => $label) {
        $curr = $ln[$id][$m]   ?? null;
        $prev = $ln[$id][$m12] ?? null;
        $chg[$id][$m] = ($curr === null || $prev === null) ? null : (($curr - $prev) * 100);
    }
}

// z-Scores je Serie
$z = [];
foreach ($series as $id => $label) {
    $vals = array_values(array_filter($chg[$id] ?? [], fn($x) => $x !== null));
    if (count($vals) < 2) continue;
    $mean = array_sum($vals) / count($vals);
    $var  = 0.0;
    foreach ($vals as $v) $var += ($v - $mean) * ($v - $mean);
    $std = sqrt($var / (count($vals) - 1));
    if ($std == 0) $std = 1;
    foreach ($chg[$id] as $m => $v) {
        $z[$id][$m] = ($v === null) ? null : (($v - $mean) / $std);
    }
}

// Proxy: Mittel der z-Scores pro Monat
$proxy = [];
for ($i = 12; $i < count($months); $i++) {
    $m = $months[$i];
    $bucket = [];
    foreach ($series as $id => $label) {
        if (isset($z[$id][$m]) && $z[$id][$m] !== null) $bucket[] = $z[$id][$m];
    }
    if (!empty($bucket)) $proxy[$m] = array_sum($bucket) / count($bucket);
}

$proxyMonths = array_keys($proxy);
$proxyVals   = array_values($proxy);

// SMA(3)
$proxySMA3 = [];
for ($i = 0; $i < count($proxyVals); $i++) {
    if ($i < 2) { $proxySMA3[] = null; continue; }
    $slice = array_slice($proxyVals, $i - 2, 3);
    $proxySMA3[] = round(array_sum($slice) / count($slice), 3);
}

$current = end($proxyVals);
$avg3 = count($proxyVals) >= 3 ? round(array_sum(array_slice($proxyVals, -3)) / 3, 3) : round($current, 3);
$avgAll = round(array_sum($proxyVals) / count($proxyVals), 3);

function classify($v) {
    if ($v >= 1.0)  return 'ultraexpansiv';
    if ($v >= 0.5)  return 'expansiv';
    if ($v <= -1.0) return 'ultrarestriktiv';
    if ($v <= -0.5) return 'restriktiv';
    return 'neutral';
}
$signal = classify($current);

// Letzter Monat
$latestMonth = end($months);
$latest_values = [];
foreach ($series as $id => $label) {
    $latest_values[] = [
        'name'  => $label,
        'value' => isset($aligned[$id][$latestMonth]) ? round($aligned[$id][$latestMonth], 2) : null,
        'date'  => $latestMonth
    ];
}

echo json_encode([
    'labels'        => $proxyMonths,
    'data'          => array_map(fn($v) => round($v, 3), $proxyVals),
    'avg3Data'      => $proxySMA3,
    'currentScore'  => round($current, 3),
    'average3M'     => $avg3,
    'averageAll'    => $avgAll,
    'signal'        => $signal,
    'latest_values' => $latest_values,
    'subscores'     => [
        'us' => isset($z['WALCL'][$latestMonth]) ? round($z['WALCL'][$latestMonth], 3) : null,
        'eu' => isset($z['ECBASSETS'][$latestMonth]) ? round($z['ECBASSETS'][$latestMonth], 3) : null,
    ]
]);
exit;