"""
PrivacyCreds — complete demo.

Run from the project root:
    python -m examples.demo
"""

import tempfile
from pathlib import Path

from privacy_creds import Issuer, PlayerWallet, GameVerifier, FileStorage


def main():
    # Use a temp directory so we don't clutter the project
    with tempfile.TemporaryDirectory() as tmpdir:
        storage = FileStorage(Path(tmpdir))

        # --- 1. Issuer setup (done once by KYC provider) ---
        print("=== Issuer Setup ===")
        issuer = Issuer(storage=storage)
        issuer.generate_keys()
        print("Issuer keys generated.\n")

        # --- 2. Issue credentials after verifying identity ---
        print("=== Issuing Credentials ===")
        alice_cred = issuer.issue(user_id="alice01", age=22, country="GB")
        bob_cred = issuer.issue(user_id="bob02", age=16, country="US")
        print(f"Alice: age_over_18={alice_cred.claims['age_over_18']}")
        print(f"Bob:   age_over_18={bob_cred.claims['age_over_18']}\n")

        # --- 3. Player wallets (on player devices) ---
        print("=== Wallet Setup ===")
        alice_wallet = PlayerWallet(user_id="alice01", storage_dir=storage.base_dir)
        alice_wallet.setup(alice_cred.to_dict())

        bob_wallet = PlayerWallet(user_id="bob02", storage_dir=storage.base_dir)
        bob_wallet.setup(bob_cred.to_dict())
        print("Wallets created with device-bound keys.\n")

        # --- 4. Game verification ---
        print("=== Game Session ===")
        verifier = GameVerifier(issuer_pubkey_pem=issuer.get_public_key_pem())

        for name, wallet in [("Alice", alice_wallet), ("Bob", bob_wallet)]:
            challenge = verifier.create_challenge()
            proof = wallet.prove(challenge)
            result = verifier.verify(proof, required_age=18)
            print(f"{name}: {result}")

        # --- 5. Attack tests ---
        print("\n=== Security Tests ===")

        # Tampered challenge
        challenge = verifier.create_challenge()
        proof = alice_wallet.prove(challenge)
        proof["challenge"] = verifier.create_challenge()
        result = verifier.verify(proof)
        print(f"Tampered challenge: {result}")

        # Tampered claim
        challenge = verifier.create_challenge()
        proof = alice_wallet.prove(challenge)
        proof["credential"]["claims"]["country"] = "XX"
        result = verifier.verify(proof)
        print(f"Tampered credential: {result}")

        print("\nDone.")


if __name__ == "__main__":
    main()
