<?php
if(PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}

$root = str_replace('\\','/',dirname(__DIR__));
$configDir = $root.'/includes/config';
$path = $configDir.'/nexora.secrets.php';
if(!is_dir($configDir) || !is_writable($configDir)) {
    fwrite(STDERR, "ERROR: includes/config no es escribible por este usuario.\n");
    exit(1);
}

$data = array();
if(is_file($path) && is_readable($path)) {
    $loaded = include($path);
    if(is_array($loaded)) $data = $loaded;
}

$names = array('NEXORA_PAYMENT_SIGNING_KEY','NEXORA_CRON_API_KEY');
$created = array();
foreach($names as $name) {
    if(!isset($data[$name]) || !is_string($data[$name]) || strlen(trim($data[$name])) < 24 || stripos($data[$name], 'CHANGE_ME') !== false) {
        $data[$name] = bin2hex(random_bytes(32));
        $created[] = $name;
    }
}
ksort($data);
$body = "<?php\n/** Nexora managed secrets. Never publish this file. */\nreturn ".var_export($data,true).";\n";
$tmp = $path.'.tmp.'.bin2hex(random_bytes(5));
if(file_put_contents($tmp,$body,LOCK_EX) === false) {
    fwrite(STDERR,"ERROR: no se pudo escribir el temporal.\n");
    exit(1);
}
@chmod($tmp,0600);
if(!@rename($tmp,$path)) {
    @unlink($tmp);
    fwrite(STDERR,"ERROR: no se pudo publicar nexora.secrets.php.\n");
    exit(1);
}
@chmod($path,0600);

foreach($names as $name) {
    $fingerprint = strtoupper(substr(hash('sha256',$data[$name]),0,12));
    echo $name.': '.(in_array($name,$created,true) ? 'GENERADA' : 'EXISTENTE').' · huella '.$fingerprint."\n";
}
echo "OK: los valores no se imprimen en consola.\n";
