"""Async flight search using the AsyncDuffel client.

Usage:
    python examples/async_search.py

Requires DUFFEL_TOKEN environment variable or a test_api_key file in the project root.
"""

import asyncio
import os
from pathlib import Path

from duffelbag import AsyncDuffel

TOKEN = os.environ.get("DUFFEL_TOKEN") or Path("test_api_key").read_text().strip()


async def main():
    async with AsyncDuffel(token=TOKEN) as client:
        # Search for round-trip flights
        offer_request = await client.offer_requests.create(
            slices=[
                {
                    "origin": "LHR",
                    "destination": "CDG",
                    "departure_date": "2026-07-01",
                },
                {
                    "origin": "CDG",
                    "destination": "LHR",
                    "departure_date": "2026-07-08",
                },
            ],
            passengers=[{"type": "adult"}],
            cabin_class="economy",
            return_offers=True,
        )

        print(f"Found {len(offer_request.offers)} round-trip offers LHR <-> CDG\n")

        # Use async iteration to page through offers sorted by price
        count = 0
        async for offer in client.offers.list(offer_request.id, sort="total_amount"):
            outbound = offer.slices[0].segments[0]
            inbound = offer.slices[1].segments[0]
            print(
                f"  {offer.owner.name:20s}"
                f"  {offer.total_amount:>8s} {offer.total_currency}"
                f"  Out: {outbound.departing_at:%H:%M}"
                f"  Return: {inbound.departing_at:%H:%M}"
            )
            count += 1
            if count >= 10:
                break

        print(f"\n(showed {count} of {len(offer_request.offers)} offers)")


asyncio.run(main())
