"""Fetch and display seat map information for a flight offer.

Usage:
    python examples/seat_maps.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 a flight
offer_request = client.offer_requests.create(
    slices=[{
        "origin": "LHR",
        "destination": "JFK",
        "departure_date": "2026-06-15",
    }],
    passengers=[{"type": "adult"}],
    return_offers=True,
)

offer = offer_request.offers[0]
print(f"Fetching seat maps for offer {offer.id}...")
print(f"  {offer.owner.name}: {offer.slices[0].segments[0].origin.iata_code}"
      f" -> {offer.slices[0].segments[-1].destination.iata_code}\n")

seat_maps = client.seat_maps.list(offer.id)

if not seat_maps:
    print("No seat maps available for this offer.")
else:
    for i, seat_map in enumerate(seat_maps):
        segment = offer.slices[0].segments[i] if i < len(offer.slices[0].segments) else None
        if segment:
            print(f"Segment: {segment.origin.iata_code} -> {segment.destination.iata_code}"
                  f" ({segment.marketing_carrier.iata_code}{segment.marketing_carrier_flight_number})")

        for cabin in seat_map.cabins:
            print(f"\n  Cabin: {cabin.cabin_class}  (Rows: {len(cabin.rows)})")
            for row in cabin.rows[:3]:  # Show first 3 rows
                seats = []
                for section in row.sections:
                    for element in section.elements:
                        if element.type == "seat":
                            designator = element.designator or "?"
                            available = "free" if element.available_services else "taken"
                            seats.append(f"{designator}({available})")
                print(f"    Row {row.sections[0].elements[0].designator[:2] if row.sections[0].elements else '?':>3s}: {' '.join(seats)}")
            if len(cabin.rows) > 3:
                print(f"    ... and {len(cabin.rows) - 3} more rows")

client.close()
