"""Book a flight and then cancel it.

This example demonstrates the full booking lifecycle:
  1. Search for offers
  2. Select the cheapest offer
  3. Create an order (instant booking with balance payment)
  4. Retrieve and inspect the order
  5. Cancel the order

Usage:
    python examples/book_and_cancel_flight.py

Requires DUFFEL_TOKEN environment variable or a test_api_key file in the project root.
Uses Duffel's test mode, so no real bookings are made.
"""

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)

# --- 1. Search ---

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

# --- 2. Select cheapest ---

offers = sorted(offer_request.offers, key=lambda o: float(o.total_amount))
offer = offers[0]
passenger = offer.passengers[0]

print(f"Selected offer: {offer.id}")
print(f"  {offer.owner.name} — {offer.total_amount} {offer.total_currency}")

# --- 3. Book ---

print("\nCreating order...")
order = client.orders.create(
    selected_offers=[offer.id],
    passengers=[{
        "id": passenger.id,
        "title": "mr",
        "gender": "m",
        "given_name": "Test",
        "family_name": "Traveller",
        "born_on": "1990-01-01",
        "email": "test@example.com",
        "phone_number": "+442080000000",
    }],
    type="instant",
    payments=[{
        "type": "balance",
        "amount": offer.total_amount,
        "currency": offer.total_currency,
    }],
)

print(f"Order created: {order.id}")
print(f"  Booking reference: {order.booking_reference}")

# --- 4. Retrieve ---

retrieved = client.orders.get(order.id)
print(f"\nRetrieved order {retrieved.id}:")
print(f"  Passengers: {len(retrieved.passengers)}")
for slc in retrieved.slices:
    origin = slc.segments[0].origin.iata_code
    dest = slc.segments[-1].destination.iata_code
    print(f"  Slice: {origin} -> {dest}")

# --- 5. Cancel ---

print("\nCancelling order...")
cancellation = client.order_cancellations.create(order_id=order.id)
print(f"  Cancellation created: {cancellation.id}")
print(f"  Refund amount: {cancellation.refund_amount} {cancellation.refund_currency}")

confirmed = client.order_cancellations.confirm(cancellation.id)
print(f"  Cancellation confirmed!")

client.close()
print("\nDone.")
