"""Tests for signer.py — keypair loading and signing."""

import json
from pathlib import Path

from solders.keypair import Keypair

from corpo.signer import generate_keypair, load_keypair, save_keypair


def test_load_keypair(tmp_keypair):
    kp, kp_path = tmp_keypair
    loaded = load_keypair(kp_path)
    assert loaded.pubkey() == kp.pubkey()


def test_generate_keypair():
    kp1 = generate_keypair()
    kp2 = generate_keypair()
    assert kp1.pubkey() != kp2.pubkey()


def test_save_and_load_roundtrip(tmp_path):
    kp = generate_keypair()
    path = tmp_path / "roundtrip.json"
    save_keypair(kp, path)

    # File should be readable JSON array of 64 ints
    raw = json.loads(path.read_text())
    assert len(raw) == 64

    loaded = load_keypair(path)
    assert loaded.pubkey() == kp.pubkey()


def test_save_keypair_permissions(tmp_path):
    kp = generate_keypair()
    path = tmp_path / "perms.json"
    save_keypair(kp, path)
    import stat
    mode = path.stat().st_mode & 0o777
    assert mode == 0o600


def test_save_keypair_creates_parents(tmp_path):
    kp = generate_keypair()
    path = tmp_path / "nested" / "dir" / "kp.json"
    save_keypair(kp, path)
    assert path.exists()
