<?php
require_once __DIR__ . "/_bootstrap.php";

try {
    $pdo = fxh_optimizer_pdo();
    fxh_optimizer_require_license($pdo);

    if (!isset($_FILES["csv"]) || $_FILES["csv"]["error"] !== UPLOAD_ERR_OK) {
        fxh_send(400, ["error"=>"CSV upload required"]);
    }

    $tmp = $_FILES["csv"]["tmp_name"];
    $fh = fopen($tmp, "rb");
    if (!$fh) fxh_send(500, ["error"=>"Unable to read upload"]);

    $headers = null;
    $rows = [];
    $maxRows = 50000; // production-safe cap

    while (($line = fgetcsv($fh)) !== false) {
        if ($headers === null) {
            $headers = array_map(fn($h)=>trim((string)$h), $line);
            continue;
        }
        if (count($rows) >= $maxRows) break;

        $row = [];
        foreach ($headers as $i => $h) {
            $row[$h] = $line[$i] ?? "";
        }
        $rows[] = $row;
    }
    fclose($fh);

    if (!$headers) fxh_send(422, ["error"=>"CSV missing headers"]);

    // ===============================
    // VALIDATE REQUIRED PERFORMANCE METRICS
    // ===============================
    $requiredMetrics = [
        'net_profit',
        'max_dd',
        'profit_factor',
        'win_rate'
    ];
    
    $missing = [];
    foreach ($requiredMetrics as $m) {
        if (!in_array($m, $headers, true)) {
            $missing[] = $m;
        }
    }
    
    if ($missing) {
        fxh_send(422, [
            "error"   => "CSV missing required performance metrics",
            "missing" => $missing,
            "hint"    => "Export FULL Strategy Tester CSV from TradingView (Overview → Export)"
        ]);
    }

    
    fxh_send(200, [
        "status" => "ok",
        "headers" => $headers,
        "rows" => $rows
    ]);

} catch (Throwable $e) {
    fxh_send(500, ["error"=>"Server error", "details"=>$e->getMessage()]);
}
