"""Basic usage examples for Kawaa Python SDK."""

import os

from kawaa import Kawaa, KawaaError

# Get API key from environment variable
API_KEY = os.environ.get("KAWAA_API_KEY", "your-api-key")


def single_verification():
    """Verify a single email address."""
    print("\n=== Single Email Verification ===")

    client = Kawaa(API_KEY)

    try:
        result = client.verify("john.doe@gmail.com")

        print(f"Email: {result.email}")
        print(f"Status: {result.status.value}")
        print(f"Score: {result.score}/100")
        print(f"Valid: {result.is_valid}")
        print(f"Deliverable: {result.is_deliverable}")
        print(f"Flags:")
        print(f"  - Disposable: {result.flags.disposable}")
        print(f"  - Role account: {result.flags.role}")
        print(f"  - Free provider: {result.flags.free_provider}")
        print(f"  - Catch-all: {result.flags.catch_all}")

        if result.suggestion:
            print(f"Did you mean: {result.suggestion}")

    except KawaaError as e:
        print(f"Error: {e}")


def batch_verification():
    """Verify multiple emails in batch."""
    print("\n=== Batch Email Verification ===")

    client = Kawaa(API_KEY)

    emails = [
        "valid@example.com",
        "john.doe@gmail.com",
        "test@mailinator.com",  # Disposable
        "info@company.com",  # Role account
        "invalid-email",  # Invalid format
        "john.doe@gmail.com",  # Duplicate
    ]

    try:
        # Start batch job
        job = client.verify_batch(emails)

        print(f"Job ID: {job.job_id}")
        print(f"Total submitted: {job.total_submitted}")
        print(f"Duplicates removed: {job.duplicates_removed}")
        print(f"Unique emails: {job.unique_emails}")
        print(f"Credits used: {job.credits_used}")
        print(f"Credits remaining: {job.credits_remaining}")

        # Wait for completion
        print("\nWaiting for job to complete...")
        result = client.wait_for_job(job.job_id, poll_interval=1.0, timeout=60)

        print(f"\nJob completed!")
        print(f"Valid: {result.valid_count}")
        print(f"Invalid: {result.invalid_count}")
        print(f"Risky: {result.risky_count}")
        print(f"Unknown: {result.unknown_count}")

        print("\nResults:")
        for r in result.results:
            status_icon = (
                "✓" if r.is_valid else "✗" if r.status.value == "invalid" else "?"
            )
            print(f"  {status_icon} {r.email}: {r.status.value} (score: {r.score})")

    except KawaaError as e:
        print(f"Error: {e}")


def batch_with_webhook():
    """Verify emails with webhook notification."""
    print("\n=== Batch Verification with Webhook ===")

    client = Kawaa(API_KEY)

    emails = ["test1@example.com", "test2@example.com"]

    try:
        job = client.verify_batch(
            emails,
            webhook_url="https://your-server.com/webhook",
            webhook_secret="your-secret-key",
        )

        print(f"Job ID: {job.job_id}")
        print("Webhook will be called when job completes.")

    except KawaaError as e:
        print(f"Error: {e}")


def download_results():
    """Download results from a completed job."""
    print("\n=== Download Results ===")

    client = Kawaa(API_KEY)

    # First, create and complete a job
    emails = ["test1@example.com", "test2@example.com"]

    try:
        result = client.verify_batch_and_wait(emails, timeout=60)
        job_id = result.job_id

        # Download as JSON
        print("\nJSON format:")
        download = client.download_results(job_id, format="json")
        print(f"Result count: {download.result_count}")
        for r in download.results:
            print(f"  {r.email}: {r.status.value}")

        # Download as CSV
        print("\nCSV format:")
        csv_data = client.download_results(job_id, format="csv")
        print(csv_data[:500])  # Print first 500 chars

    except KawaaError as e:
        print(f"Error: {e}")


def check_account():
    """Check account information."""
    print("\n=== Account Information ===")

    client = Kawaa(API_KEY)

    try:
        account = client.get_account()

        print(f"User ID: {account.user_id}")
        print(f"Email: {account.email}")
        print(f"Plan: {account.plan}")
        print(f"Credits remaining: {account.credits_remaining}")
        print(f"Credits used: {account.credits_used}")

    except KawaaError as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    print("Kawaa Python SDK Examples")
    print("=" * 50)

    single_verification()
    batch_verification()
    check_account()

    # Uncomment to run additional examples:
    # batch_with_webhook()
    # download_results()
