import math
import time

from hallpass_sdk import (
    generate_agent_key_material,
    sign_compact_jwt,
    verify_compact_jwt,
    decode_compact_jwt,
)


def test_sign_verify_roundtrip():
    km = generate_agent_key_material()
    payload = {"sub": "test", "iat": math.floor(time.time())}
    jwt = sign_compact_jwt(payload, km.private_jwk)

    assert jwt.count(".") == 2

    result = verify_compact_jwt(jwt, km.public_jwk)
    assert result.valid is True
    assert result.payload["sub"] == "test"
    assert result.header["alg"] == "ES256"


def test_reject_tampered_token():
    km = generate_agent_key_material()
    jwt = sign_compact_jwt({"sub": "test"}, km.private_jwk)
    tampered = jwt[:-5] + "XXXXX"
    result = verify_compact_jwt(tampered, km.public_jwk)
    assert result.valid is False


def test_reject_wrong_key():
    km1 = generate_agent_key_material()
    km2 = generate_agent_key_material()
    jwt = sign_compact_jwt({"sub": "test"}, km1.private_jwk)
    result = verify_compact_jwt(jwt, km2.public_jwk)
    assert result.valid is False


def test_decode_without_verification():
    km = generate_agent_key_material()
    jwt = sign_compact_jwt({"sub": "test", "foo": "bar"}, km.private_jwk)
    result = decode_compact_jwt(jwt)
    assert result.valid is True
    assert result.payload["sub"] == "test"
    assert result.payload["foo"] == "bar"


def test_decode_malformed():
    result = decode_compact_jwt("only.two")
    assert result.valid is False
