<?php
use kornrunner\Secp256k1;
use kornrunner\Serializer\HexSignatureSerializer;
use kornrunner\Signature\Signature;
use kornrunner\Util\Buffer;




function signTransaction(array $transaction, string $privateKey): array {
    $rawData = $transaction['raw_data'];

    // 1. 将 raw_data 转为 JSON 字符串
    $rawDataJson = json_encode($rawData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($rawDataJson === false) {
        throw new \Exception("Invalid raw_data: " . json_last_error_msg());
    }

    // 2. 计算 SHA256 哈希（二进制形式）
    $msgHash = hash('sha256', $rawDataJson, true); // raw binary

    // 3. 构造私钥 buffer（二进制）
    $privateKeyBin = hex2bin($privateKey);
    if ($privateKeyBin === false || strlen($privateKeyBin) !== 32) {
        throw new \Exception("Invalid private key format");
    }

    // 4. 签名
    $secp256k1 = new Secp256k1();
    $signature = $secp256k1->sign($msgHash, $privateKeyBin);

    // 5. 生成 HEX 签名（包含 recovery ID）
    $serializer = new HexSignatureSerializer();
    $fullHex = $serializer->serialize($signature); // 130 hex chars: r + s + v (65 bytes)

    // ⚠️ Tron 要求 r + s（不带 v） => 64 字节，即 128 字符的 hex 字符串
    $r = substr($fullHex, 0, 64);
    $s = substr($fullHex, 64, 64);
    $sigHex = $r . $s;

    return [
        'txID' => $transaction['txID'],
        'raw_data' => $transaction['raw_data'],
        'signature' => [$sigHex],
    ];
}
