<?php
require_once __DIR__ . '/../../../engine/bewertungsmethoden/bewertung_strategic-profiles.php';

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

	$mode = $params['profile']
		 ?? ($_POST['strategic-profile'] ?? $_POST['strategic_profile'] ?? $_POST['profile'] ?? 'high_performer');
	if (!in_array($mode, ['high_performer','solide','ertragreich'], true)) $mode = 'high_performer';
	
	$minScorePercent = (float)($params['minScore'] ?? $_POST['min_score_percent'] ?? 50);
	$wantPremium = (bool)($params['premium'] ?? $_POST['premium_flags'] ?? false);

	// Debug: Laufzeit-Trace
	if (!empty($_POST['debug_sp'])) {
		echo "TRACE|strategic-profiles|mode={$mode}|premium=" . ($wantPremium?'1':'0') . "\\n";
		flush();
	}

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

	$messages = [];
	$rows     = [];
	$hits     = 0;
	$symbols  = [];

	foreach ($tickers as $entry) {
		$s = is_array($entry)
			? ($entry['symbol'] ?? $entry['ticker'] ?? $entry['Code'] ?? $entry['s'] ?? null)
			: $entry;

		if (!$s) continue;
		$symbols[] = strtoupper(trim((string)$s));
	}
	$symbols = array_values(array_unique(array_filter($symbols)));

	foreach ($symbols as $sym) {
		if (!empty($_POST['debug_sp'])) { echo "SYMBOL|$sym\n"; flush(); }
		
		try {
			$res = bewertung_strategic_profiles_score($sym, $mode, ['premium'=>$wantPremium]);
		} catch (Throwable $e) {
			$messages[] = "WARN|{$sym}|–|".$e->getMessage();
			continue; // nächstes Symbol
		}
		
		$percent  = (float)($res['percent'] ?? 0);
		$name     = $res['name'] ?? $sym;
		$exchange = $res['exchange'] ?? '';
		$rationale= array_slice($res['why'] ?? [], 0, 3);
		$premium  = $res['premium'] ?? null;
		
		$label = rtrim(rtrim(number_format($percent, 2, '.', ''), '0'), '.');
		$messages[] = "CHECK|{$sym}|–|{$label}/100|{$name}|strategic/{$mode}";

		if ($percent >= $minScorePercent) {
			$hits++;
			$dataJson = json_encode([
				'score_percent' => $percent,
				'score_label'   => "{$label}/100",
				'method_detail' => $mode,
				'sector'        => $res['sector'] ?? null,
				'rationale'     => $rationale,
				'premium'       => $premium,
			], JSON_UNESCAPED_UNICODE);

			$methodStr = "strategic-profiles:{$mode}";
			$ins->execute([$scanId, $sym, $exchange, $name, $percent, $dataJson, $methodStr]);

			$rows[] = [
				'ticker'   => $sym, 'name' => $name, 'exchange' => $exchange,
				'name'     => $name,
				'exchange' => $exchange,
				'score'    => $percent, 'method' => $methodStr,
				'method'   => 'strategic-profiles',
			];
		}
	}

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