<?php
require_once __DIR__ . '/../../../engine/bewertungsmethoden/bewertung_oversold.php';

function run_scoring(array $tickers, array $params): array {
	/** @var PDO $pdo */
	$pdo       = $params['pdo'];
	$scanId    = $params['scanId'];
	$direction = $params['direction'] ?? 'buy';

	$opts = [
		'rsi_len'      => isset($params['rsi_len'])   ? (int)$params['rsi_len']   : 14,
		'rsi_buy'      => isset($params['rsi_buy'])   ? (float)$params['rsi_buy'] : 30.0,
		'rsi_sell'     => isset($params['rsi_sell'])  ? (float)$params['rsi_sell']: 70.0,
		'mom_len'      => 63,
		'mom_buy'      => isset($params['mom_buy'])   ? (float)$params['mom_buy'] : -20.0,
		'mom_sell'     => isset($params['mom_sell'])  ? (float)$params['mom_sell']: 20.0,
		'macd_fast'    => isset($params['macd_fast'])   ? (int)$params['macd_fast']   : 12,
		'macd_slow'    => isset($params['macd_slow'])   ? (int)$params['macd_slow']   : 26,
		'macd_signal'  => isset($params['macd_signal']) ? (int)$params['macd_signal'] : 9,
		'macd_mode'    => $params['macd_mode'] ?? 'Kein MACD-Kriterium',
		'trend_len'    => isset($params['r2ar_len']) ? (int)$params['r2ar_len'] : 100,
		'r2ar_src'     => strtolower($params['r2ar_src'] ?? 'close'),
		'enable_trend' => in_array(strtolower((string)($params['enable_trend'] ?? '0')), ['1','true','on','yes'], true),
		'enable_vola'  => in_array(strtolower((string)($params['enable_vola']  ?? '1')), ['1','true','on','yes'], true),
		'vola_mult'    => isset($params['vola_mult']) ? (float)$params['vola_mult'] : 0.95,
	];

	$ins = $pdo->prepare("
		INSERT INTO scan_results (scan_id, ticker, exchange, name, score, data_json, method)
		VALUES (?, ?, ?, ?, ?, ?, 'oversold')
		ON DUPLICATE KEY UPDATE
			score     = VALUES(score),
			data_json = VALUES(data_json),
			name      = VALUES(name),
			exchange  = VALUES(exchange)
	");

	$messages  = [];
	$rows      = [];   // für Live-Preview
	$totalHits = 0;    // Gesamt-Trefferzähler (für scan_start.php)

	foreach ($tickers as $entry) {
		$symbol = is_array($entry) ? ($entry['symbol'] ?? $entry['Code'] ?? '') : $entry;
		$symbol = strtoupper(trim((string)$symbol));
		if ($symbol === '') continue;

		$res = oversold_evaluate($symbol, array_merge($opts, ['direction' => $direction]));
		if (!($res['success'] ?? false)) continue;
		if (!($res['signal'] ?? false))  continue;

		$percent      = (int)($res['score'] ?? 0);        // 0/66/100 (für DB)
		$criteriaHits = (int)($res['hits']  ?? 0);        // 0..3 (per Aktie)
		$total        = (int)($res['total'] ?? 3);
		$label        = $res['score_label'] ?? ("{$criteriaHits}/{$total}");

		$name     = $res['name']     ?? $symbol;
		$exchange = $res['exchange'] ?? '';

		$dataJson = json_encode([
			'details'     => $res['details'] ?? [],
			'hits'        => $criteriaHits,
			'total'       => $total,
			'score_label' => $label,
			'kind'        => $res['signal_kind'] ?? null,
		], JSON_UNESCAPED_UNICODE);

		// persistieren (Prozent bleiben als score in der DB)
		$ins->execute([$scanId, $res['ticker'], $exchange, $name, $percent, $dataJson]);

		// Stream-Log: Label "2/3" bzw. "3/3"
		$messages[] = "CHECK|{$res['ticker']}|–|{$label}|{$name}|{$res['signal_kind']}";
		$totalHits++;

		// Live-Preview (für Anzeige kannst du $label oder $percent verwenden)
		$rows[] = [
			'ticker'   => $res['ticker'],
			'name'     => $name,
			'exchange' => $exchange,
			'score'    => $label,     // Anzeige "2/3" | "3/3"; für numerische Sortierung -> $percent
			'method'   => 'oversold',
		];
	}

	return [
		'messages' => $messages,
		'hits'     => $totalHits,            // WICHTIG: Gesamtzahl an Treffern
		'scanned'  => count($tickers),
		'data'     => $rows,
	];
}
