"""Simple example of using 1Password CLI injection functions.

This example demonstrates the basic usage of inject_string_1password
and inject_dictionary_1password functions.

Prerequisites:
- 1Password CLI installed (op command available)
- User authenticated (op signin completed)
- Test vault and items set up in 1Password
"""

from scottzach1.onepassword_cli import (
    OnePasswordNotAuthenticatedError,
    OnePasswordNotInstalledError,
    SecretInjectionError,
    inject_dictionary_1password,
    inject_string_1password,
)


def example_string_injection() -> None:
    """Example of injecting a single secret from a string."""
    print("Example 1: String Injection")
    print("-" * 50)

    # Replace these with actual secret references from your 1Password vault
    secret_reference = "op://vault/item/password"

    try:
        # This will inject the actual secret value
        secret_value = inject_string_1password(secret_reference)
        print("Secret injected successfully!")
        print(f"Length of secret: {len(secret_value)} characters")
    except OnePasswordNotInstalledError:
        print("Error: 1Password CLI is not installed")
        print("Install it from: https://developer.1password.com/docs/cli/get-started/")
    except OnePasswordNotAuthenticatedError:
        print("Error: Not authenticated with 1Password")
        print("Run 'op signin' to authenticate")
    except SecretInjectionError as e:
        print(f"Error: Failed to inject secret: {e}")

    print()


def example_string_with_no_secrets() -> None:
    """Example showing that strings without secrets are returned unchanged."""
    print("Example 2: String Without Secrets")
    print("-" * 50)

    plain_text = "This is just a regular string with no secrets"
    result = inject_string_1password(plain_text)

    print(f"Original: {plain_text}")
    print(f"Result: {result}")
    print(f"Unchanged: {plain_text == result}")
    print()


def example_dictionary_injection() -> None:
    """Example of injecting secrets from a dictionary while preserving types."""
    print("Example 3: Dictionary Injection")
    print("-" * 50)

    # Replace these with actual secret references from your 1Password vault
    config = {
        "database_url": "op://vault/database/url",
        "api_key": "op://vault/api/key",
        "port": 5432,  # Non-secret values are preserved
        "debug": True,
        "timeout": None,
        "retries": 3,
    }

    try:
        # Inject secrets while preserving non-string types
        injected_config = inject_dictionary_1password(config)

        print("Configuration with injected secrets:")
        print(f"  Database URL: {'<injected>' if 'op://' not in injected_config['database_url'] else 'not injected'}")
        print(f"  API Key: {'<injected>' if 'op://' not in injected_config['api_key'] else 'not injected'}")
        print(f"  Port: {injected_config['port']} (type: {type(injected_config['port']).__name__})")
        print(f"  Debug: {injected_config['debug']} (type: {type(injected_config['debug']).__name__})")
        print(f"  Timeout: {injected_config['timeout']}")
        print(f"  Retries: {injected_config['retries']}")
    except OnePasswordNotInstalledError:
        print("Error: 1Password CLI is not installed")
    except OnePasswordNotAuthenticatedError:
        print("Error: Not authenticated with 1Password")
    except SecretInjectionError as e:
        print(f"Error: Failed to inject secrets: {e}")

    print()


def example_nested_dictionary() -> None:
    """Example of injecting secrets from nested dictionaries."""
    print("Example 4: Nested Dictionary Injection")
    print("-" * 50)

    config = {
        "database": {
            "host": "op://vault/db/host",
            "port": 5432,
            "username": "op://vault/db/username",
            "password": "op://vault/db/password",
        },
        "api": {
            "key": "op://vault/api/key",
            "endpoint": "https://api.example.com",
        },
        "features": {
            "enabled": ["auth", "analytics"],
            "debug": False,
        },
    }

    try:
        injected_config = inject_dictionary_1password(config)

        print("Nested configuration with injected secrets:")
        print("  Database:")
        print(f"    Host: {'<injected>' if 'op://' not in injected_config['database']['host'] else 'not injected'}")
        print(f"    Port: {injected_config['database']['port']}")
        print("  API:")
        print(f"    Endpoint: {injected_config['api']['endpoint']}")
        print("  Features:")
        print(f"    Enabled: {injected_config['features']['enabled']}")
        print(f"    Debug: {injected_config['features']['debug']}")
    except OnePasswordNotInstalledError:
        print("Error: 1Password CLI is not installed")
    except OnePasswordNotAuthenticatedError:
        print("Error: Not authenticated with 1Password")
    except SecretInjectionError as e:
        print(f"Error: Failed to inject secrets: {e}")

    print()


def example_in_place_modification() -> None:
    """Example of modifying a dictionary in place."""
    print("Example 5: In-Place Dictionary Modification")
    print("-" * 50)

    config = {"api_key": "op://vault/api/key", "timeout": 30}

    print(f"Original config ID: {id(config)}")

    try:
        # Modify the dictionary in place
        result = inject_dictionary_1password(config, in_place=True)

        print(f"Result config ID: {id(result)}")
        print(f"Same object: {result is config}")
        print(f"API Key injected: {'op://' not in config['api_key']}")
        print(f"Timeout preserved: {config['timeout']}")
    except OnePasswordNotInstalledError:
        print("Error: 1Password CLI is not installed")
    except OnePasswordNotAuthenticatedError:
        print("Error: Not authenticated with 1Password")
    except SecretInjectionError as e:
        print(f"Error: Failed to inject secrets: {e}")

    print()


def main() -> None:
    """Run all examples."""
    print("=" * 50)
    print("1Password CLI Injection Examples")
    print("=" * 50)
    print()

    # Run all examples
    example_string_injection()
    example_string_with_no_secrets()
    example_dictionary_injection()
    example_nested_dictionary()
    example_in_place_modification()

    print("=" * 50)
    print("Examples completed!")
    print("=" * 50)


if __name__ == "__main__":
    main()
