from __future__ import annotations

from amcs.crypto.ed25519 import b64encode, generate_keypair
from amcs.sdk.client import AMCSClient
from amcs.store.sqlite import SQLiteEventStore


def test_root_checkpoint_roundtrip_verification(tmp_path) -> None:
    store = SQLiteEventStore(str(tmp_path / "events.db"))
    client = AMCSClient(store=store, agent_id="agent-cp")
    client.append("interaction.append", {"message": "hello"})
    client.append("memory.upsert", {"memory": "prefers tea"})

    private_key, public_key = generate_keypair()
    checkpoint = client.create_root_checkpoint(
        signer_private_key_b64=b64encode(private_key),
        signer_kid="registry-main",
    )
    assert checkpoint["sequence"] == 2
    assert len(checkpoint["memory_root"]) == 64
    assert client.verify_root_checkpoint(
        checkpoint=checkpoint,
        signer_public_key_b64=b64encode(public_key),
    )


def test_root_checkpoint_verification_fails_on_tamper(tmp_path) -> None:
    store = SQLiteEventStore(str(tmp_path / "events.db"))
    client = AMCSClient(store=store, agent_id="agent-cp")
    client.append("interaction.append", {"message": "hello"})

    private_key, public_key = generate_keypair()
    checkpoint = client.create_root_checkpoint(
        signer_private_key_b64=b64encode(private_key),
        signer_kid="registry-main",
    )
    checkpoint["memory_root"] = "f" * 64
    assert not client.verify_root_checkpoint(
        checkpoint=checkpoint,
        signer_public_key_b64=b64encode(public_key),
    )


def test_root_checkpoint_rejects_empty_log(tmp_path) -> None:
    store = SQLiteEventStore(str(tmp_path / "events.db"))
    client = AMCSClient(store=store, agent_id="agent-empty")
    private_key, _ = generate_keypair()
    try:
        client.create_root_checkpoint(
            signer_private_key_b64=b64encode(private_key),
            signer_kid="registry-main",
        )
    except ValueError as exc:
        assert "empty agent log" in str(exc)
    else:
        raise AssertionError("expected ValueError for empty agent log")
