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

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

    $j = fxh_json_input();
    $best = $j["best"] ?? null;

    if (!is_array($best) || count($best) < 1) {
        fxh_send(422, ["error"=>"Missing best results"]);
    }

    // Build CSV from "raw" rows if present; else from params
    $rowsOut = [];
    foreach ($best as $b) {
        if (is_array($b) && isset($b["raw"]) && is_array($b["raw"])) {
            $rowsOut[] = $b["raw"];
        } elseif (is_array($b) && isset($b["params"]) && is_array($b["params"])) {
            $r = [];
            foreach ($b["params"] as $kv) {
                $parts = explode("=", $kv, 2);
                $r[$parts[0]] = $parts[1] ?? "";
            }
            $rowsOut[] = $r;
        }
    }

    if (count($rowsOut) < 1) {
        fxh_send(422, ["error"=>"No exportable rows"]);
    }

    // Determine headers union
    $headers = [];
    foreach ($rowsOut as $r) {
        foreach ($r as $k => $_) {
            if (!in_array($k, $headers, true)) $headers[] = $k;
        }
    }

    // Output CSV
    header_remove("Content-Type");
    header("Content-Type: text/csv; charset=utf-8");
    header("Content-Disposition: attachment; filename=FXH_best_parameters.csv");

    $out = fopen("php://output", "wb");
    fputcsv($out, $headers);

    foreach ($rowsOut as $r) {
        $line = [];
        foreach ($headers as $h) $line[] = $r[$h] ?? "";
        fputcsv($out, $line);
    }
    fclose($out);
    exit;

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