"""Example usage of hezor_common.security.signature module.

This example demonstrates:
1. Generating Ed25519 key pairs
2. Serializing and deserializing keys
3. Signing and verifying messages
4. Signing and verifying JSON data
5. Password-protected key serialization

Usage
-----
Run all examples:
    uv run examples/security/signature_example.py

Run specific example:
    uv run examples/security/signature_example.py 1
    uv run examples/security/signature_example.py 2
    uv run examples/security/signature_example.py 3
    uv run examples/security/signature_example.py 4
    uv run examples/security/signature_example.py 5
    uv run examples/security/signature_example.py 6

List available examples:
    uv run examples/security/signature_example.py --list
"""

import sys

from hezor_common.security import (
    deserialize_private_key,
    deserialize_public_key,
    generate_key_pair,
    serialize_private_key,
    serialize_public_key,
    sign,
    sign_json,
    sign_message,
    verify,
    verify_json_signature,
    verify_signature,
)


def example_1_basic_key_generation():
    """Example 1: Generate and use Ed25519 key pair."""
    print("=== Example 1: Basic Key Generation ===")

    # Generate a new key pair
    private_key, public_key = generate_key_pair()
    print("✓ Generated Ed25519 key pair")

    # Sign a message
    message = b"Hello, World!"
    signature = sign_message(private_key, message)
    print(f"✓ Signed message: {message.decode()}")
    print(f"  Signature length: {len(signature)} bytes")

    # Verify the signature
    is_valid = verify_signature(public_key, signature, message)
    print(f"✓ Signature verification: {is_valid}")

    # Try with wrong message
    wrong_valid = verify_signature(public_key, signature, b"Wrong message")
    print(f"✓ Wrong message verification: {wrong_valid}")
    print()


def example_2_key_serialization():
    """Example 2: Serialize and deserialize keys."""
    print("=== Example 2: Key Serialization ===")

    # Generate keys
    private_key, public_key = generate_key_pair()

    # Serialize without password
    private_pem = serialize_private_key(private_key)
    public_pem = serialize_public_key(public_key)

    print("✓ Serialized keys to PEM format")
    print(f"  Private key (first 50 chars): {private_pem[:50].decode()}...")
    print(f"  Public key (first 50 chars): {public_pem[:50].decode()}...")

    # Deserialize
    loaded_private = deserialize_private_key(private_pem)
    loaded_public = deserialize_public_key(public_pem)
    print("✓ Deserialized keys from PEM format")

    # Verify they work
    message = b"Test message"
    signature = sign_message(loaded_private, message)
    is_valid = verify_signature(loaded_public, signature, message)
    print(f"✓ Loaded keys work correctly: {is_valid}")
    print()


def example_3_password_protected_key():
    """Example 3: Password-protected private key."""
    print("=== Example 3: Password-Protected Key ===")

    # Generate key
    private_key, _ = generate_key_pair()

    # Serialize with password
    password = b"my_secure_password_123"
    encrypted_pem = serialize_private_key(private_key, password=password)

    print("✓ Serialized private key with password protection")
    print(f"  Encrypted PEM (first 60 chars): {encrypted_pem[:60].decode()}...")

    # Deserialize with password
    loaded_private = deserialize_private_key(encrypted_pem, password=password)
    print("✓ Successfully loaded password-protected key")

    # Verify it works
    message = b"Secret message"
    signature = sign_message(loaded_private, message)
    print(f"✓ Password-protected key works: signature length = {len(signature)}")
    print()


def example_4_json_signing():
    """Example 4: Sign and verify JSON data."""
    print("=== Example 4: JSON Data Signing ===")

    # Generate keys
    private_key, public_key = generate_key_pair()

    # Prepare JSON data
    data = {
        "user_id": "alice_123",
        "action": "login",
        "timestamp": 1706025600,
        "ip_address": "192.168.1.100",
    }

    print(f"✓ Original data: {data}")

    # Sign JSON
    signature = sign_json(private_key, data)
    print("✓ Signed JSON data")
    print(f"  Signature: {signature.hex()[:32]}...")

    # Verify signature
    is_valid = verify_json_signature(public_key, signature, data)
    print(f"✓ Signature verification: {is_valid}")

    # Try with modified data
    tampered_data = data.copy()
    tampered_data["user_id"] = "bob_456"
    tampered_valid = verify_json_signature(public_key, signature, tampered_data)
    print(f"✓ Tampered data verification: {tampered_valid}")
    print()


def example_5_key_persistence():
    """Example 5: Save and load keys from files."""
    print("=== Example 5: Key Persistence ===")

    from pathlib import Path

    # Generate keys
    private_key, public_key = generate_key_pair()

    # Get current script directory
    script_dir = Path(__file__).parent
    private_path = script_dir / "private_key.pem"
    public_path = script_dir / "public_key.pem"

    # Serialize and save keys
    private_pem = serialize_private_key(private_key, password=b"file_password")
    public_pem = serialize_public_key(public_key)

    private_path.write_bytes(private_pem)
    public_path.write_bytes(public_pem)

    print("✓ Saved keys to files")
    print(f"  Private: {private_path}")
    print(f"  Public: {public_path}")

    # Load keys from files
    loaded_private_pem = private_path.read_bytes()
    loaded_public_pem = public_path.read_bytes()

    loaded_private = deserialize_private_key(loaded_private_pem, password=b"file_password")
    loaded_public = deserialize_public_key(loaded_public_pem)

    print("✓ Loaded keys from files")

    # Verify they work
    test_data = {"message": "File persistence test"}
    signature = sign_json(loaded_private, test_data)
    is_valid = verify_json_signature(loaded_public, signature, test_data)
    print(f"✓ Loaded keys work correctly: {is_valid}")

    print("✓ Key files saved for use in other examples")
    print("  (Will be used by Example 6)")

    print()


def example_6_complete_workflow():
    """Example 6: Complete authentication workflow."""
    print("=== Example 6: Complete Authentication Workflow ===")

    from pathlib import Path

    # Get current script directory
    script_dir = Path(__file__).parent
    private_path = script_dir / "private_key.pem"
    public_path = script_dir / "public_key.pem"

    # Check if keys exist from Example 5
    if not (private_path.exists() and public_path.exists()):
        print("✗ Key files not found!")
        print("  Please run Example 5 first to generate and save keys:")
        print(f"  uv run {sys.argv[0]} 5")
        print()
        return

    print("✓ Server: Using key pair from files (generated in Example 5)")
    print(f"  Private: {private_path}")
    print(f"  Public: {public_path}")

    # Server publishes public key
    print("✓ Server: Published public key")

    # Client receives public key
    print("✓ Client: Received server's public key")

    # Server creates and signs authentication token
    auth_token = {
        "user_id": "user_42",
        "role": "admin",
        "expires_at": 1706112000,
        "permissions": ["read", "write", "delete"],
    }

    # password should match the one used in example 5
    token_signature = sign(private_path, auth_token, password=b"file_password")
    print("✓ Server: Signed authentication token for user_42")

    # Client verifies token
    is_token_valid = verify(public_path, token_signature, auth_token)
    print(f"✓ Client: Token verification result: {is_token_valid}")

    # Attacker tries to modify token
    fake_token = auth_token.copy()
    fake_token["role"] = "super_admin"
    is_fake_valid = verify(public_path, token_signature, fake_token)
    print(f"✓ Client: Fake token verification result: {is_fake_valid}")

    print()


def list_examples():
    """List all available examples."""
    examples = {
        1: ("Basic Key Generation", example_1_basic_key_generation),
        2: ("Key Serialization", example_2_key_serialization),
        3: ("Password-Protected Key", example_3_password_protected_key),
        4: ("JSON Data Signing", example_4_json_signing),
        5: ("Key Persistence", example_5_key_persistence),
        6: ("Complete Authentication Workflow", example_6_complete_workflow),
    }

    print("Available examples:")
    for num, (name, _) in examples.items():
        print(f"  {num}. {name}")
    print()
    print("Usage:")
    print(f"  uv run {sys.argv[0]} [example_number]")
    print(f"  uv run {sys.argv[0]}              # Run all examples")
    print(f"  uv run {sys.argv[0]} --list       # List examples")

    return examples


def main():
    """Run examples based on command line arguments."""
    examples = {
        1: ("Basic Key Generation", example_1_basic_key_generation),
        2: ("Key Serialization", example_2_key_serialization),
        3: ("Password-Protected Key", example_3_password_protected_key),
        4: ("JSON Data Signing", example_4_json_signing),
        5: ("Key Persistence", example_5_key_persistence),
        6: ("Complete Authentication Workflow", example_6_complete_workflow),
    }

    # Parse command line arguments
    if len(sys.argv) > 1:
        arg = sys.argv[1]

        if arg in ["--list", "-l", "list"]:
            list_examples()
            return

        try:
            example_num = int(arg)
            if example_num not in examples:
                print(f"Error: Example {example_num} not found.")
                print()
                list_examples()
                sys.exit(1)

            # Run single example
            name, func = examples[example_num]
            print("=" * 60)
            print(f"hezor_common.security.signature - Example {example_num}")
            print("=" * 60)
            print()
            func()
            print("=" * 60)
            print(f"Example {example_num} completed successfully!")
            print("=" * 60)
            return

        except ValueError:
            print(f"Error: Invalid argument '{arg}'")
            print()
            list_examples()
            sys.exit(1)

    # Run all examples
    print("=" * 60)
    print("hezor_common.security.signature - Usage Examples")
    print("=" * 60)
    print()

    for func in [
        example_1_basic_key_generation,
        example_2_key_serialization,
        example_3_password_protected_key,
        example_4_json_signing,
        example_5_key_persistence,
        example_6_complete_workflow,
    ]:
        func()

    print("=" * 60)
    print("All examples completed successfully!")
    print("=" * 60)


if __name__ == "__main__":
    main()
