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

import asyncio
import os

from kawaa import AsyncKawaa, KawaaError

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


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

    async with AsyncKawaa(API_KEY) as client:
        try:
            result = await 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}")

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


async def batch_verification():
    """Verify multiple emails asynchronously."""
    print("\n=== Async Batch Verification ===")

    async with AsyncKawaa(API_KEY) as client:
        emails = [
            "user1@example.com",
            "user2@example.com",
            "user3@example.com",
        ]

        try:
            # Start batch job
            job = await client.verify_batch(emails)
            print(f"Job ID: {job.job_id}")

            # Wait for completion
            result = await client.wait_for_job(job.job_id, timeout=60)

            print(f"Valid: {result.valid_count}")
            print(f"Invalid: {result.invalid_count}")

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


async def parallel_verification():
    """Verify multiple emails in parallel."""
    print("\n=== Parallel Verification ===")

    async with AsyncKawaa(API_KEY) as client:
        emails = [
            "user1@example.com",
            "user2@example.com",
            "user3@example.com",
            "user4@example.com",
            "user5@example.com",
        ]

        try:
            # Verify all emails in parallel
            tasks = [client.verify(email) for email in emails]
            results = await asyncio.gather(*tasks, return_exceptions=True)

            for email, result in zip(emails, results):
                if isinstance(result, Exception):
                    print(f"  ✗ {email}: Error - {result}")
                else:
                    status_icon = "✓" if result.is_valid else "✗"
                    print(f"  {status_icon} {email}: {result.status.value}")

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


async def batch_with_progress():
    """Show progress while waiting for batch job."""
    print("\n=== Batch with Progress ===")

    async with AsyncKawaa(API_KEY) as client:
        emails = [f"user{i}@example.com" for i in range(20)]

        try:
            job = await client.verify_batch(emails)
            print(f"Job ID: {job.job_id}")

            # Poll with progress updates
            while True:
                status = await client.get_job_status(job.job_id)
                print(
                    f"\rProgress: {status.progress_percent:.1f}% "
                    f"({status.processed_emails}/{status.total_emails})",
                    end="",
                    flush=True,
                )

                if status.is_completed:
                    print("\nCompleted!")
                    break

                if status.is_failed:
                    print("\nFailed!")
                    break

                await asyncio.sleep(1)

            # Get final results
            result = await client.get_job_status(job.job_id, include_results=True)
            print(f"Valid: {result.valid_count}, Invalid: {result.invalid_count}")

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


async def main():
    """Run all async examples."""
    print("Kawaa Async Python SDK Examples")
    print("=" * 50)

    await single_verification()
    await batch_verification()
    await parallel_verification()

    # Uncomment to run additional examples:
    # await batch_with_progress()


if __name__ == "__main__":
    asyncio.run(main())
