<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	http_response_code(405);
	echo json_encode(['error' => 'Nur POST-Anfragen erlaubt']);
	exit;
}

require_once '../../engine/engine.php';

function respondWithError($message) {
	http_response_code(500);
	echo json_encode(['error' => $message]);
	exit;
}

$method      = $_POST['method'] ?? 'fundamentale-kriterien';
$sourceFile  = $_POST['source_file'] ?? '';
$startIndex  = max(0, (int)($_POST['start_index'] ?? 0));
$limitCount  = min(300, max(1, (int)($_POST['limit_count'] ?? 100)));
$pauseSec    = max(0, (float)($_POST['pause_sec'] ?? 0.2));

$filePath = realpath(__DIR__ . '/../tickers/ticker-listen/' . basename($sourceFile));
if (!$filePath || !is_file($filePath)) {
	respondWithError("Dateifehler: '$sourceFile' ist keine gültige Datei");
}
$json = file_get_contents($filePath);
$tickerData = json_decode($json, true);
if (!is_array($tickerData) || count($tickerData) === 0) {
	respondWithError("Keine gültigen Ticker gefunden");
}
$tickers = array_slice($tickerData, $startIndex, $limitCount);

$chunkSize = match (true) {
	count($tickers) <= 30  => 1,
	count($tickers) <= 200 => 5,
	default                => 10
};

$chunks = array_chunk($tickers, $chunkSize);

if (!$sourceFile) {
	respondWithError("source_file fehlt");
}
if (!in_array($method, ['fundamentale-kriterien', 'oversold', 'saisonalitaet', 'saisonalitaet100', 'minervini', 'strategic-profiles', 'strategic-profiles', 'chart-whale-patterns'])) {
	respondWithError("Unbekannte Methode: $method");
}

$scanId = uniqid('scan_', true);

try {
	// 1. Scan-Meta einfügen
	$stmtInsert = $pdo->prepare("
		INSERT INTO scan_meta 
		(scan_id, method, source_file, start_index, limit_count, pause_sec, scanned_total) 
		VALUES (?, ?, ?, ?, ?, ?, 0)
	");
	$success = $stmtInsert->execute([$scanId, $method, $sourceFile, $startIndex, $limitCount, $pauseSec]);

	if (!$success) {
		respondWithError("Fehler beim Speichern in der Datenbank.");
	}

	// 2. Alte Chunks zu diesem Scan löschen
	$stmtCleanup = $pdo->prepare("DELETE FROM scan_chunks WHERE scan_id = ?");
	$stmtCleanup->execute([$scanId]);
	
	// 3. Neue Chunks speichern
	$stmtInsertChunk = $pdo->prepare("
		INSERT INTO scan_chunks (scan_id, chunk_index, tickers_json, chunk_hash)
		VALUES (?, ?, ?, ?)
	");
	
	foreach ($chunks as $index => $chunk) {
		$tickerSymbols = array_map(fn($t) => is_array($t) ? ($t['symbol'] ?? $t['Code'] ?? '') : $t, $chunk);
		sort($tickerSymbols);
		$chunkHash = md5(implode(',', $tickerSymbols));
		$tickersJson = json_encode($tickerSymbols);
	
		$stmtInsertChunk->execute([$scanId, $index, $tickersJson, $chunkHash]);
	}

	// 4. Antwort ausgeben
	echo json_encode(['scan_id' => $scanId]);

} catch (Throwable $e) {
	respondWithError("Datenbankfehler: " . $e->getMessage());
}