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

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

	// Schwellenwert in Prozent (0..100)
	$minScorePercent = (int)($params['minScore'] ?? $params['scoreMin'] ?? $params['score_min'] ?? 0);

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

	// Symbole normalisieren
	$symbols = [];
	foreach ($tickers as $entry) {
		$s = is_array($entry) ? ($entry['symbol'] ?? $entry['Code'] ?? '') : $entry;
		$s = strtoupper(trim((string)$s));
		if ($s !== '') $symbols[] = $s;
	}
	if (!$symbols) return ['messages' => [], 'hits' => 0, 'scanned' => 0, 'data' => []];

	$messages = [];
	$hits     = 0;
	$rows     = []; // <- für Live-Preview

	foreach ($symbols as $symbol) {
		$res = bewertung_fundamental_score(
			$symbol,
			$params['asof'] ?? null,
			$params['target_pe_override'] ?? null,
			$params['data_rating'] ?? null,
			[]
		);

		$points  = (int)($res['score']    ?? 0);      // 0..25 (Punkte)
		$percent = (float)($res['percent'] ?? 0.0);   // 0..100

		if ($percent < $minScorePercent) {
			continue;
		}

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

		// Persistiere Prozent als 'score'
		$scorePersist = (int)round($percent);

		$dataJson = json_encode([
			'total'      => (int)($res['total'] ?? 0),
			'percent'    => $percent,
			'points'     => $points,
			'details'    => $res['details'] ?? [],
			'fairValues' => $res['fairValues'] ?? null,
		], JSON_UNESCAPED_UNICODE);

		$ins->execute([$scanId, $symbol, $exchange, $name, $scorePersist, $dataJson]);

		// Stream-Log
		$messages[] = "CHECK|{$symbol}|{$scorePersist}|{$name}|fundamental ok";
		$hits++;

		// Live-Preview-Zeile
		$rows[] = [
			'ticker'   => $symbol,
			'name'     => $name,
			'exchange' => $exchange,
			'score'    => $scorePersist,
			'method'   => 'fundamental',
		];
	}

	return [
		'messages' => $messages,
		'hits'     => $hits,
		'scanned'  => count($symbols),
		'data'     => $rows,    // <- wichtig für Vorschautabelle & Fallback
	];
}
