<?php
require_once __DIR__ . '/../../../engine/bewertungsmethoden/bewertung_whale-patterns.php';

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

	$minScore = isset($params['min_score_whales']) ? (int)$params['min_score_whales'] : 80;

	// Wrapper-Optionen → Engine-Optionen
	$opts = [
		// patterns_evaluate kennt timeseries/weights/benchmark.
		// Wir nehmen genug Historie für Weekly-Patterns.
		'timeseries' => isset($params['lookback_bars']) ? max(220, (int)$params['lookback_bars']) : 420,
		'benchmark'  => $params['benchmark'] ?? 'SPY',
		// 'weights' kann bei Bedarf durchgereicht werden:
		'weights'    => $params['weights'] ?? null,
	];

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

	$messages=[]; $rows=[]; $totalHits=0;

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

		// Engine aufrufen (liefert: symbol,name,exchange,score,signals,weights,pivot_price)
		$eng = patterns_evaluate($symbol, array_filter($opts, fn($v) => $v!==null));
		if (!is_array($eng) || isset($eng['error'])) continue;

		$percent = (int)($eng['score'] ?? 0);
		if ($percent < $minScore) continue;

		$ticker   = $eng['symbol']   ?? $symbol;
		$name     = $eng['name']     ?? $symbol;
		$exchange = $eng['exchange'] ?? '';

		// "hits/total": wie viele Signals sind ok?
		$signals = is_array($eng['signals'] ?? null) ? $eng['signals'] : [];
		$total   = count($signals);
		$hits    = 0;
		foreach ($signals as $s) if (!empty($s['ok'])) $hits++;

		// Top-Pattern bestimmen (höchster Beitrag: score * Gewicht)
		$topPattern = null; $topVal = -1;
		$weights = $eng['weights'] ?? [];
		foreach ($signals as $nameKey => $s) {
			$raw = isset($s['score']) ? max(0, min(100, (int)$s['score'])) : (!empty($s['ok']) ? 100 : 0);
			$w   = isset($weights[$nameKey]) ? (int)$weights[$nameKey] : 0;
			$val = $raw * $w;
			if ($val > $topVal) { $topVal = $val; $topPattern = $nameKey; }
		}
		$kind = $topPattern ? ("Whale-".$topPattern) : 'Whales';

		// Daten fürs Frontend
		$dataJson = json_encode([
			'timeframe'    => '1d',
			'patterns'     => $signals,          // komplette Signalstruktur
			'details'      => $signals,          // alias, damit UI was hat
			'pivot'        => isset($eng['pivot_price']) ? ['level' => (float)$eng['pivot_price']] : null,
			'hits'         => $hits,
			'total'        => $total,
			'score_label'  => (string)$percent,
			'signal_kind'  => $kind,
		], JSON_UNESCAPED_UNICODE);

		$ins->execute([$scanId, $ticker, $exchange, $name, $percent, $dataJson]);

		$messages[] = "CHECK|{$ticker}|–|{$percent}|{$name}|{$kind}";
		$totalHits++;

		$rows[] = [
			'ticker'   => $ticker,
			'name'     => $name,
			'exchange' => $exchange,
			'score'    => $percent, // numerisch sortierbar
			'method'   => 'chart-whale-patterns',
		];
	}

	return [
		'messages' => $messages,
		'hits'     => $totalHits,
		'scanned'  => count($tickers),
		'data'     => $rows,
	];
}
