"""Non-custodial keypair loading and transaction signing."""

import json
from base64 import b64decode, b64encode
from pathlib import Path

import httpx
from solders.keypair import Keypair
from solders.transaction import Transaction


def load_keypair(path: str | Path) -> Keypair:
    """Load a Solana keypair from a JSON file (solana-keygen format).

    The file contains a JSON array of 64 integers representing the secret key bytes.
    """
    path = Path(path).expanduser()
    raw = json.loads(path.read_text())
    return Keypair.from_bytes(bytes(raw))


def generate_keypair() -> Keypair:
    """Generate a new random keypair."""
    return Keypair()


def save_keypair(keypair: Keypair, path: str | Path) -> None:
    """Save a keypair to a JSON file in solana-keygen format."""
    path = Path(path).expanduser()
    path.parent.mkdir(parents=True, exist_ok=True)
    raw = list(bytes(keypair))
    path.write_text(json.dumps(raw))
    path.chmod(0o600)


def sign_and_send(
    tx_b64: str,
    keypair: Keypair,
    rpc_url: str,
) -> str:
    """Sign a base64-encoded unsigned transaction and send it to the RPC.

    Returns the transaction signature as a base58 string.
    """
    tx_bytes = b64decode(tx_b64)
    tx = Transaction.from_bytes(tx_bytes)

    msg_bytes = bytes(tx.message)
    sig = keypair.sign_message(msg_bytes)

    signed_tx = Transaction.populate(tx.message, [sig])
    signed_bytes = bytes(signed_tx)
    signed_b64 = b64encode(signed_bytes).decode("ascii")

    payload = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "sendTransaction",
        "params": [
            signed_b64,
            {"encoding": "base64", "skipPreflight": False},
        ],
    }
    resp = httpx.post(rpc_url, json=payload, timeout=30.0)
    resp.raise_for_status()
    result = resp.json()

    if "error" in result:
        err = result["error"]
        msg = err.get("message", str(err))
        raise RuntimeError(f"RPC error: {msg}")

    return result["result"]
