"""Example usage of JWT module.

This example demonstrates JWT encoding and decoding using Ed25519 asymmetric encryption.

Usage
-----
Run the example:
    uv run examples/security/jwt_example.py
"""

import sys
from pathlib import Path

from hezor_common.security import decode, encode

# Get the directory where this script is located
SCRIPT_DIR = Path(__file__).parent
PRIVATE_KEY_FILE = SCRIPT_DIR / "private_key.pem"
PUBLIC_KEY_FILE = SCRIPT_DIR / "public_key.pem"


def main():
    """Demonstrate JWT encoding and decoding with file-based keys."""
    print("=" * 60)
    print("JWT Module - Simple Usage Example")
    print("=" * 60)
    print()

    # Check if key files exist
    if not PRIVATE_KEY_FILE.exists() or not PUBLIC_KEY_FILE.exists():
        print("✗ Key files not found!")
        print(f"  Expected: {PRIVATE_KEY_FILE}")
        print(f"  Expected: {PUBLIC_KEY_FILE}")
        print()
        print("Please generate keys first by running:")
        print("  uv run examples/security/signature_example.py 5")
        print()
        sys.exit(1)

    print(f"✓ Using key files from {SCRIPT_DIR}")
    print()

    # Create JWT payload
    payload = {
        "user_id": "user123",
        "username": "alice",
        "role": "admin",
        "permissions": ["read", "write", "delete"],
    }
    print("Creating JWT with payload:")
    for key, value in payload.items():
        print(f"  {key}: {value}")
    print()

    # Encode JWT (expires in 1 hour)
    # Note: password must match the one used in signature_example.py example 5
    token = encode(PRIVATE_KEY_FILE, payload, password=b"file_password", expires_in=3600)
    print("✓ Encoded JWT token (expires in 1 hour):")
    print(f"  {token[:50]}...")
    print(f"  {token[-30:]}")
    print(f"  Token length: {len(token)} bytes")
    print()

    # Decode JWT
    decoded = decode(PUBLIC_KEY_FILE, token)
    print("✓ Decoded JWT payload:")
    for key, value in decoded.items():
        print(f"  {key}: {value}")
    print()

    # Verify data integrity
    assert decoded["user_id"] == payload["user_id"]
    assert decoded["username"] == payload["username"]
    assert decoded["role"] == payload["role"]
    print("✓ Payload integrity verified successfully!")
    print()

    print("=" * 60)
    print("Example completed successfully!")
    print("=" * 60)


if __name__ == "__main__":
    main()
