from hallpass_sdk import (
    generate_agent_key_material,
    create_message_proof_bundle,
    verify_message_proof_bundle,
    create_agent_challenge_response,
    create_delegation_jwt,
    decode_compact_jwt,
)


def test_create_and_verify_message_bundle():
    km = generate_agent_key_material()
    bundle = create_message_proof_bundle(
        principal_username="alice",
        body="Hello from agent",
        author_label="Test Agent",
        key_material=km,
    )

    assert bundle.principal_username == "alice"
    assert bundle.author_label == "Test Agent"
    assert bundle.signer_did == km.did
    assert bundle.message_jwt.count(".") == 2

    result = verify_message_proof_bundle(bundle)
    assert result.signature_valid is True
    assert result.key_matches is True
    assert result.message["body"] == "Hello from agent"


def test_verify_detects_tampered_jwt():
    km = generate_agent_key_material()
    bundle = create_message_proof_bundle(
        principal_username="alice", body="Hello", author_label="Agent", key_material=km
    )
    bundle.message_jwt = bundle.message_jwt[:-5] + "XXXXX"
    result = verify_message_proof_bundle(bundle)
    assert result.signature_valid is False


def test_challenge_response():
    km = generate_agent_key_material()
    jwt = create_agent_challenge_response(challenge="abc123", key_material=km)
    assert jwt.count(".") == 2
    decoded = decode_compact_jwt(jwt)
    assert decoded.payload["challenge"] == "abc123"
    assert decoded.header["typ"] == "hallpass-agent-proof+jwt"


def test_delegation_jwt():
    km = generate_agent_key_material()
    import math, time

    now = math.floor(time.time())
    payload = {
        "sub": "alice",
        "user_id": "u1",
        "agent_id": "a1",
        "agent_did": km.did,
        "iat": now,
        "nbf": now,
        "exp": now + 3600,
        "jti": "test-jti",
        "typ": "hallpass-profile-authorization",
    }
    jwt = create_delegation_jwt(payload, km.private_jwk)
    assert jwt.count(".") == 2
    decoded = decode_compact_jwt(jwt)
    assert decoded.payload["sub"] == "alice"
    assert decoded.header["typ"] == "hallpass-profile-authorization+jwt"
