<?php
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors','0');
set_error_handler(function($s,$m,$f,$l){ throw new ErrorException($m,0,$s,$f,$l); });

try {
    require_once __DIR__ . '/../../engine/engine.php';
    require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';
    require_once __DIR__ . '/../../engine/bewertungsmethoden/forecast/runner.php';

    $symbol = $_GET['symbol'] ?? $_POST['symbol'] ?? '';
    $h      = (int)($_GET['h'] ?? $_POST['h'] ?? 20);
    if (!$symbol) { echo json_encode(['ok'=>false,'error'=>'symbol fehlt']); exit; }
    if (!function_exists('fmp_multi')) { throw new RuntimeException('fmp_multi() nicht gefunden'); }

    // ---- Multi-Fetch (zentral) ----
    $query = ['timeseries'=>5000];
    $multi = fmp_multi([
        'prices' => [
            'key'   => 'historical_price_full', // an deinen Registry-Key angepasst
            'vars'  => ['symbol'=>$symbol],
            'query' => $query,
        ],
        'profile' => [
            'key'  => 'profile',
            'vars' => ['symbol'=>$symbol],
        ],
    ]);

    // Preise normalisieren (verschiedene Shapes abfangen)
    $rows = $multi['prices'] ?? null;
    if (isset($rows['historical']) && is_array($rows['historical'])) $rows = $rows['historical'];
    if (!is_array($rows)) throw new RuntimeException('Ticker-Daten konnten nicht geladen werden');

    // alt->neu sortiert + Bars bauen
    $rows = array_values(array_reverse($rows));
    $bars = [];
    foreach ($rows as $r) {
        $c = $r['adjClose'] ?? $r['close'] ?? null;
        $o = $r['open'] ?? ($r['adjOpen'] ?? null);
        $hig = $r['high'] ?? ($r['adjHigh'] ?? null);
        $low = $r['low']  ?? ($r['adjLow']  ?? null);
        if ($c===null || $hig===null || $low===null) continue;
        $bars[] = [
            't' => $r['date'] ?? '',
            'o' => (float)$o, 'h' => (float)$hig, 'l' => (float)$low, 'c' => (float)$c,
            'v' => (int)($r['volume'] ?? 0),
        ];
    }
    if (count($bars) < 300) { echo json_encode(['ok'=>false,'error'=>'Zu wenig Historie (min 300 Bars)']); exit; }

    // optionale Metadaten aus Profile
    $name = null; $exchange = null;
    if (!empty($multi['profile'])) {
        $p = is_array($multi['profile']) && isset($multi['profile'][0]) ? $multi['profile'][0] : $multi['profile'];
        if (is_array($p)) {
            $name = $p['companyName'] ?? $p['company_name'] ?? null;
            $exchange = $p['exchange'] ?? $p['exchangeShortName'] ?? null;
        }
    }

    // ---- Forecast ausführen ----
    if (!function_exists('Forecast\\forecast_run')) throw new RuntimeException('Forecast\\forecast_run() nicht gefunden');
    $atr = isset($_GET['atr']) ? (float)$_GET['atr'] : (isset($_POST['atr']) ? (float)$_POST['atr'] : 1.5);
    $res = Forecast\forecast_run($bars, max(1,$h), $atr);
    
    if (function_exists('db_pdo')) {
      $pdo = db_pdo();
      $stmt = $pdo->prepare("INSERT INTO forecast_log
        (symbol,horizon,p_up,p10,p50,p90,exp_ret,exp_maxdd,confidence,trend,vol,close)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
      $m = $res['meta']['regime'] ?? null;
      $stmt->execute([
        $symbol, $h,
        $res['prob_up'], $res['retiles']['p10'], $res['retiles']['p50'], $res['retiles']['p90'],
        $res['expectations']['exp_ret'], $res['expectations']['exp_maxdd'],
        $res['meta']['confidence'] ?? null,
        $m['trend'] ?? null, $m['vol'] ?? null,
        $res['risk']['close'] ?? null
      ]);
    }

    // Antwort anreichern
    $res['symbol']   = $symbol;
    $res['scanned']  = count($bars);
    if ($name)     $res['name'] = $name;
    if ($exchange) $res['exchange'] = $exchange;
    
    $res['last_date'] = $bars[count($bars)-1]['t'] ?? null;

    echo json_encode($res);

} catch (Throwable $e) {
    echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
