"""Search for flights and display results.

Usage:
    python examples/search_flights.py

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

import os
from pathlib import Path

from duffelbag import Duffel

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

client = Duffel(token=TOKEN)

# --- Search for one-way flights from London to New York ---

offer_request = client.offer_requests.create(
    slices=[{
        "origin": "LHR",
        "destination": "JFK",
        "departure_date": "2026-06-15",
    }],
    passengers=[{"type": "adult"}],
    cabin_class="economy",
    return_offers=True,
)

print(f"Offer request {offer_request.id} returned {len(offer_request.offers)} offers\n")

# --- Show the five cheapest offers ---

offers = sorted(offer_request.offers, key=lambda o: float(o.total_amount))

for offer in offers[:5]:
    slc = offer.slices[0]
    segments = slc.segments
    stops = len(segments) - 1
    route = " -> ".join(seg.origin.iata_code for seg in segments) + f" -> {segments[-1].destination.iata_code}"

    print(f"  {offer.owner.name:20s}  {offer.total_amount:>8s} {offer.total_currency}")
    print(f"    Route: {route}  ({stops} stop{'s' if stops != 1 else ''} )")
    print(f"    Departs: {segments[0].departing_at}  Arrives: {segments[-1].arriving_at}")
    print()

# --- You can also paginate through offers separately ---

print("Paginating offers (first page of 5):")
page = client.offers.list(offer_request.id, limit=5, sort="total_amount").page()
for offer in page:
    print(f"  {offer.id}  {offer.total_amount} {offer.total_currency}")

client.close()
