<?php
require_once __DIR__ . '/../../../engine/bewertungsmethoden/bewertung_saisonalitaet.php';
if (!function_exists('fmp_multi')) {
	require_once __DIR__ . '/../../../engine/api-handling/fmp_client.php';
}


function run_scoring(array $tickers, array $params): array
{
	/** @var PDO $pdo */
	$pdo              = $params['pdo'];
	$scanId           = $params['scanId'];
	$monthsAhead      = (int)($params['saison_months'] ?? 3);
	$monthsAhead      = max(1, min(12, $monthsAhead));
	$thresholdScore   = (int)($params['saison_threshold_score'] ?? 85); // wie Legacy
	$thresholdHitRate = (int)($params['saison_threshold_hit']   ?? 90); // wie Legacy

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

	// Symbole normalisieren + evtl. Meta aus Input (Fallback)
	$symbols = [];
	$fallbackMeta = [];
	foreach ($tickers as $entry) {
		$s = is_array($entry) ? ($entry['symbol'] ?? $entry['Code'] ?? '') : $entry;
		$s = strtoupper(trim((string)$s));
		if ($s === '') continue;
		$symbols[] = $s;
		$fallbackMeta[$s] = [
			'name'     => $entry['name'] ?? $entry['Name'] ?? '',
			'exchange' => $entry['exchangeShortName'] ?? $entry['Exchange'] ?? '',
		];
	}
	if (!$symbols) return ['messages' => [], 'hits' => 0, 'scanned' => 0];

	// Zielmonate: ab NÄCHSTEM Monat (Legacy-Verhalten)
	$curMonth = (int)date('n');
	$targetMonths = [];
	for ($i = 1; $i <= $monthsAhead; $i++) {
		$m = (($curMonth - 1 + $i) % 12) + 1; // wrap 1..12
		$targetMonths[] = $m;
	}

	$messages = [];
	$hits     = 0;

	foreach ($symbols as $symbol) {
		// Zentrale Methode (holt historical + profile via fmp_multi)
		$season = compute_seasonality($symbol, [
			'scope'         => 'last',   // wie vorher
			'years'         => 15,
			'serietype'     => 'line',
			'with_segments' => false,
		]);

		$historicalDesc = $season['historical'] ?? [];
		if (empty($historicalDesc)) continue;

		// Hilfsfunktionen aus der zentralen Datei
		$monthly      = build_monthly_distribution_from_historical($historicalDesc);
		$statsByMonth = build_monthly_stats($monthly);

		$scores     = [];
		$match      = false;
		$monthlyOut = [];

		foreach ($targetMonths as $m) {
			if (empty($statsByMonth[$m])) { $monthlyOut[$m] = null; continue; }

			$st = $statsByMonth[$m];

			// Mindestens 5 Beobachtungen (Legacy)
			if (($st['count'] ?? 0) < 5) { $monthlyOut[$m] = null; continue; }

			$score   = (int)month_score_from_stats($st); // 0..100
			$hitRate = (int)round($st['hitRate'] ?? 0);
			$avg     = (float)($st['avg'] ?? 0);

			if ($score >= $thresholdScore && $hitRate >= $thresholdHitRate) $match = true;

			$scores[] = $score;
			$monthlyOut[$m] = [
				'avg'   => $avg,
				'hit'   => $hitRate,
				'score' => $score,
			];
		}

		$finalScore = count($scores) ? (int)round(array_sum($scores) / count($scores)) : 0;
		if (!$match || $finalScore <= 0) continue;

		// Name/Börse robust bestimmen (ohne auf Ticker zu defaulten)
		$name     = trim((string)($season['name'] ?? ($season['meta']['name'] ?? ($fallbackMeta[$symbol]['name'] ?? ''))));
		$exchange = trim((string)($season['exchange'] ?? ($season['meta']['exchange'] ?? ($fallbackMeta[$symbol]['exchange'] ?? ''))));
		
		// Wenn exchange noch leer ist, wie in Fundamental: erst profile, dann quote
		if ($exchange === '') {
			try {
				$multi = fmp_multi([
					'profile' => ['key' => 'profile', 'vars' => ['symbol' => $symbol]],
					'quote'   => ['key' => 'quote',   'vars' => ['symbol' => $symbol]],
				]);
		
				// profile
				$pArr = $multi['profile'] ?? [];
				$p    = (is_array($pArr) && isset($pArr[0])) ? $pArr[0] : (is_array($pArr) ? $pArr : []);
				if (is_array($p)) {
					if ($exchange === '' && !empty($p['exchangeShortName'])) $exchange = (string)$p['exchangeShortName'];
					if ($exchange === '' && !empty($p['exchange']))          $exchange = (string)$p['exchange'];
					// falls Name leer/gleich Ticker, hier sanft aus profile setzen
					if (($name === '' || strtoupper($name) === $symbol) && !empty($p['companyName'])) {
						$name = (string)$p['companyName'];
					}
				}
		
				// quote (Fallback für Börse)
				if ($exchange === '') {
					$qArr = $multi['quote'] ?? [];
					$q    = (is_array($qArr) && isset($qArr[0])) ? $qArr[0] : (is_array($qArr) ? $qArr : []);
					if (is_array($q)) {
						if ($exchange === '' && !empty($q['primaryExchange'])) $exchange = (string)$q['primaryExchange'];
						if ($exchange === '' && !empty($q['stockExchange']))   $exchange = (string)$q['stockExchange'];
						if ($exchange === '' && !empty($q['exchange']))        $exchange = (string)$q['exchange'];
					}
				}
			} catch (\Throwable $e) {
				// still fine; dann bleibt exchange ggf. leer
			}
		}
		
		// niemals Ticker als Name speichern
		if (strtoupper($name) === $symbol) $name = '';
		if (strcasecmp($name, $symbol) === 0) { $name = ''; }

		$dataJson = json_encode([
			'monthsConsidered' => $targetMonths,
			'saison'           => $monthlyOut,
		], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);

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

		$messages[] = "CHECK|{$symbol}|{$finalScore}|{$name}|gute Saisonalität";
		$hits++;
	}

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