"""
Test SS58 address support.

Usage:
    python tests/test_ss58.py

This verifies that SS58 addresses (like "5GrwvaEF...") work directly
in storage queries without manual conversion to hex.
"""

from pypolkadot import LightClient


# Well-known addresses for testing
# Alice on dev chains (won't exist on mainnet, but format is valid)
ALICE_SS58 = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"

# Polkadot Treasury (module account, exists on Asset Hub)
TREASURY_SS58 = "13UVJyLnbVp9RBZYFwFGyDvVd1y27Tt8tkntv6Q7JVPhFsTB"
TREASURY_HEX = "0x6d6f646c70792f74727372790000000000000000000000000000000000000000"


def test_ss58_address_in_storage_query():
    """Test that SS58 addresses work in storage queries."""
    print("\nConnecting to Asset Hub...")
    client = LightClient()

    print(f"Querying System.Account with SS58 address: {TREASURY_SS58[:20]}...")
    result_ss58 = client.storage("System", "Account", [TREASURY_SS58])
    print(f"Result (SS58): {result_ss58}")

    print(f"\nQuerying same account with hex: {TREASURY_HEX[:20]}...")
    result_hex = client.storage("System", "Account", [TREASURY_HEX])
    print(f"Result (hex): {result_hex}")

    # Both should return the same data
    assert result_ss58 == result_hex, "SS58 and hex queries should return same result"
    print("\nSS58 and hex queries match!")


def test_ss58_format_detection():
    """Test that various address formats are handled correctly."""
    print("\nConnecting to Asset Hub...")
    client = LightClient()

    # These should all work
    test_cases = [
        ("SS58 (Polkadot)", TREASURY_SS58),
        ("Hex with 0x", TREASURY_HEX),
        ("Hex without 0x", TREASURY_HEX[2:]),
    ]

    results = []
    for name, address in test_cases:
        print(f"\nTesting {name}: {address[:20]}...")
        result = client.storage("System", "Account", [address])
        results.append(result)
        print(f"  Got: {result}")

    # All should match
    assert all(r == results[0] for r in results), "All formats should return same result"
    print("\nAll address formats work correctly!")


def test_invalid_ss58_treated_as_string():
    """Test that invalid SS58 addresses don't crash (treated as strings)."""
    print("\nConnecting to Asset Hub...")
    client = LightClient()

    # This looks like SS58 length but isn't valid - should not crash
    invalid = "5InvalidAddressNotReallyValidSS58Format1234567"
    print(f"Testing invalid SS58-like string: {invalid[:20]}...")

    # This will likely fail the storage query (wrong key type) but shouldn't panic
    try:
        result = client.storage("System", "Account", [invalid])
        print(f"Result: {result}")
    except Exception as e:
        print(f"Got expected error (invalid address): {e}")


if __name__ == "__main__":
    print("=" * 60)
    print("SS58 Address Support Test")
    print("=" * 60)

    test_ss58_address_in_storage_query()
    print("\n" + "=" * 60)

    test_ss58_format_detection()
    print("\n" + "=" * 60)

    test_invalid_ss58_treated_as_string()
    print("\n" + "=" * 60)

    print("All SS58 tests passed!")
