<?php

require_once __DIR__ . '/../../../engine/bewertungsmethoden/bewertung_minervini.php';

function run_scoring(array $tickers, array $params): array
{
	$pdo       = $params['pdo'];
	$scanId    = $params['scanId'];
	$minPoints = (int)($params['scoreMin'] ?? $params['score_min'] ?? 10);

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

	$messages = [];
	$hits     = 0;

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

		$scoreData  = calculate_minervini_score($symbol);
		$scoreTotal = (int)($scoreData['score'] ?? 0);
		if ($scoreTotal < $minPoints) continue;

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

		$dataJson = json_encode([
			'technisch'           => $scoreData['technicalScore']   ?? null,
			'fundamental'         => $scoreData['fundamentalScore'] ?? null,
			'maxScore'            => $scoreData['maxScore']            ?? 14,
			'technicalCriteria'   => $scoreData['technicalCriteria']   ?? [],
			'fundamentalCriteria' => $scoreData['fundamentalCriteria'] ?? [],
			'resultMessage'       => $scoreData['resultMessage']       ?? '',
		], JSON_UNESCAPED_UNICODE);

		$stmt->execute([$scanId, $symbol, $exchange, $name, $scoreTotal, $dataJson]);

		$messages[] = "CHECK|{$symbol}|–|{$scoreTotal}|{$name}";
		$hits++;
	}

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