Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

Create cli module

Punit Arani2045521a8f0b
diff --git a/fli/cli.py b/fli/cli.py
deleted file mode 100644
index 11bbc58..0000000
--- a/fli/cli.py
+++ /dev/null
@@ -1,519 +0,0 @@
-#!/usr/bin/env python3
-
-from datetime import datetime, timedelta
-from enum import Enum
-from typing import List, Optional
-
-import typer
-from click import Context, Parameter
-from rich import box
-from rich.console import Console, Group
-from rich.panel import Panel
-from rich.table import Table
-from rich.text import Text
-from typing_extensions import Annotated
-
-from fli.models import (
- Airline,
- Airport,
- DateSearchFilters,
- FlightSegment,
- MaxStops,
- PassengerInfo,
- SeatType,
- SortBy,
-)
-from fli.search import SearchDates, SearchFlights, SearchFlightsFilters
-
-app = typer.Typer(
- help="Search for flights using Google Flights data",
- add_completion=True,
-)
-console = Console()
-
-
-class DayOfWeek(str, Enum):
- """Days of the week."""
-
- MONDAY = "monday"
- TUESDAY = "tuesday"
- WEDNESDAY = "wednesday"
- THURSDAY = "thursday"
- FRIDAY = "friday"
- SATURDAY = "saturday"
- SUNDAY = "sunday"
-
-
-def format_airport(airport: Airport) -> str:
- """Format airport code and name (first two words)."""
- name_parts = airport.value.split()[:3] # Get first three words
- name = " ".join(name_parts)
- return f"{airport.name} ({name})"
-
-
-def validate_time_range(
- ctx: Context, param: Parameter, value: Optional[str]
-) -> Optional[tuple[int, int]]:
- """Validate and parse time range in format 'start-end' (24h format)."""
- if not value:
- return None
-
- try:
- start, end = map(int, value.split("-"))
- if not (0 <= start <= 23 and 0 <= end <= 23):
- raise ValueError
- return start, end
- except ValueError:
- raise typer.BadParameter("Time range must be in format 'start-end' (e.g., 6-20)")
-
-
-def validate_date(ctx: Context, param: Parameter, value: str) -> str:
- """Validate date format."""
- try:
- datetime.strptime(value, "%Y-%m-%d")
- return value
- except ValueError:
- raise typer.BadParameter("Date must be in YYYY-MM-DD format")
-
-
-def parse_airlines(airlines: Optional[List[str]]) -> Optional[List[Airline]]:
- """Parse airlines from list of airline codes."""
- if not airlines:
- return None
-
- try:
- return [
- getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()
- ]
- except AttributeError as e:
- raise typer.BadParameter(f"Invalid airline code: {str(e)}")
-
-
-def filter_flights_by_time(flights: list, start_hour: int, end_hour: int) -> list:
- """Filter flights by departure time range."""
- return [
- flight
- for flight in flights
- if any(start_hour <= leg.departure_datetime.hour <= end_hour for leg in flight.legs)
- ]
-
-
-def filter_flights_by_airlines(flights: list, airlines: List[Airline]) -> list:
- """Filter flights by specified airlines."""
- return [flight for flight in flights if any(leg.airline in airlines for leg in flight.legs)]
-
-
-def format_duration(minutes: int) -> str:
- """Format duration in minutes to hours and minutes."""
- hours = minutes // 60
- mins = minutes % 60
- return f"{hours}h {mins}m"
-
-
-def display_flight_results(flights: list):
- """Display flight results in a beautiful format."""
- if not flights:
- console.print(Panel("No flights found matching your criteria", style="red"))
- return
-
- for i, flight in enumerate(flights, 1):
- # Create main flight info table
- table = Table(show_header=False, box=box.SIMPLE)
- table.add_column("Label", style="blue")
- table.add_column("Value", style="green")
-
- table.add_row("Price", f"${flight.price:,.2f}")
- table.add_row("Duration", format_duration(flight.duration))
- table.add_row("Stops", str(flight.stops))
-
- # Create segments table
- segments = Table(title="Flight Segments", box=box.ROUNDED)
- segments.add_column("Airline", style="cyan")
- segments.add_column("Flight", style="magenta")
- segments.add_column("From", style="yellow", width=30)
- segments.add_column("Departure", style="green")
- segments.add_column("To", style="yellow", width=30)
- segments.add_column("Arrival", style="green")
-
- for leg in flight.legs:
- segments.add_row(
- leg.airline.value,
- leg.flight_number,
- format_airport(leg.departure_airport),
- leg.departure_datetime.strftime("%H:%M %d-%b"),
- format_airport(leg.arrival_airport),
- leg.arrival_datetime.strftime("%H:%M %d-%b"),
- )
-
- # Display in a panel
- console.print(
- Panel(
- Group(
- Text(f"Flight Option {i}", style="bold blue"),
- Text(""),
- table,
- Text(""),
- segments,
- ),
- title=f"[bold]Flight {i} of {len(flights)}[/bold]",
- border_style="blue",
- box=box.ROUNDED,
- )
- )
- console.print()
-
-
-def filter_dates_by_days(dates: list, days: List[DayOfWeek]) -> list:
- """Filter dates by days of the week."""
- if not days:
- return dates
-
- day_numbers = {
- DayOfWeek.MONDAY: 0,
- DayOfWeek.TUESDAY: 1,
- DayOfWeek.WEDNESDAY: 2,
- DayOfWeek.THURSDAY: 3,
- DayOfWeek.FRIDAY: 4,
- DayOfWeek.SATURDAY: 5,
- DayOfWeek.SUNDAY: 6,
- }
-
- allowed_days = {day_numbers[day] for day in days}
- return [date_price for date_price in dates if date_price.date.weekday() in allowed_days]
-
-
-def display_date_results(dates: list):
- """Display date search results in a beautiful format."""
- if not dates:
- console.print(Panel("No flights found for these dates", style="red"))
- return
-
- table = Table(title="Cheapest Dates to Fly", box=box.ROUNDED)
- table.add_column("Date", style="cyan")
- table.add_column("Day", style="yellow")
- table.add_column("Price", style="green")
-
- for date_price in dates:
- table.add_row(
- date_price.date.strftime("%Y-%m-%d"),
- date_price.date.strftime("%A"),
- f"${date_price.price:,.2f}",
- )
-
- console.print(table)
- console.print()
-
-
-def search_flights(
- from_airport: str,
- to_airport: str,
- date: str,
- time: Optional[tuple[int, int]] = None,
- airlines: Optional[List[str]] = None,
- seat: str = "ECONOMY",
- stops: str = "ANY",
- sort: str = "CHEAPEST",
-):
- """Core flight search functionality."""
- try:
- # Parse parameters
- departure_airport = getattr(Airport, from_airport.upper())
- arrival_airport = getattr(Airport, to_airport.upper())
- seat_type = getattr(SeatType, seat.upper())
- max_stops = getattr(MaxStops, stops.upper())
- sort_by = getattr(SortBy, sort.upper())
-
- # Create search filters
- filters = SearchFlightsFilters(
- departure_airport=departure_airport,
- arrival_airport=arrival_airport,
- departure_date=date,
- passenger_info=PassengerInfo(adults=1),
- seat_type=seat_type,
- stops=max_stops,
- sort_by=sort_by,
- )
-
- # Perform search
- search_client = SearchFlights()
- flights = search_client.search(filters)
-
- if not flights:
- console.print(Panel("No flights found.", style="red"))
- raise typer.Exit(1)
-
- # Apply time filter if specified
- if time:
- start_hour, end_hour = time
- flights = filter_flights_by_time(flights, start_hour, end_hour)
-
- # Apply airline filter if specified
- airline_list = parse_airlines(airlines)
- if airline_list:
- flights = filter_flights_by_airlines(flights, airline_list)
-
- # Display results
- display_flight_results(flights)
-
- except (AttributeError, ValueError) as e:
- console.print(f"[red]Error:[/red] {str(e)}")
- raise typer.Exit(1)
-
-
-def search(
- from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
- to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
- date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)],
- time: Annotated[
- Optional[str],
- typer.Option(
- "--time",
- "-t",
- help="Time range in 24h format (e.g., 6-20)",
- callback=validate_time_range,
- ),
- ] = None,
- airlines: Annotated[
- Optional[List[str]],
- typer.Option(
- "--airlines",
- "-a",
- help="List of airline codes (e.g., BA KL)",
- ),
- ] = None,
- seat: Annotated[
- str,
- typer.Option(
- "--seat",
- "-s",
- help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
- ),
- ] = "ECONOMY",
- stops: Annotated[
- str,
- typer.Option(
- "--stops",
- "-x",
- help="Maximum number of stops (ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS)",
- ),
- ] = "ANY",
- sort: Annotated[
- str,
- typer.Option(
- "--sort",
- "-o",
- help="Sort results by (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)",
- ),
- ] = "CHEAPEST",
-):
- """
- Search for flights with flexible filtering options.
-
- Examples:\n
- fli search JFK LHR 2025-10-25 --time 6-20 --airlines BA KL\n
- fli search SFO NYC 2025-11-01 -t 9-17 --stops NON_STOP --sort DURATION\n
- fli search LAX MIA 2025-12-25 --seat BUSINESS
- """
- with console.status("[bold green]Searching for flights..."):
- search_flights(
- from_airport=from_airport,
- to_airport=to_airport,
- date=date,
- time=time,
- airlines=airlines,
- seat=seat,
- stops=stops,
- sort=sort,
- )
-
-
[email protected](invoke_without_command=True)
-def main(ctx: typer.Context):
- """
- Search for flights using Google Flights data.
- If no command is provided, the search command will be used.
- """
- # If no command is provided, show help
- if ctx.invoked_subcommand is None:
- ctx.get_help()
- raise typer.Exit()
-
-
-def cli():
- """Entry point for the CLI that handles default command."""
- import sys
-
- args = sys.argv[1:]
- if not args:
- app()
- return
-
- # If the first argument isn't a command, treat as search
- if args[0] not in ["search", "cheap", "--help", "-h"]:
- sys.argv.insert(1, "search")
-
- app()
-
-
-def cheap(
- from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
- to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
- from_date: Annotated[
- str, typer.Option("--from", help="Start date (YYYY-MM-DD)", callback=validate_date)
- ] = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d"),
- to_date: Annotated[
- str, typer.Option("--to", help="End date (YYYY-MM-DD)", callback=validate_date)
- ] = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d"),
- seat: Annotated[
- str,
- typer.Option(
- "--seat",
- "-s",
- help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
- ),
- ] = "ECONOMY",
- stops: Annotated[
- str,
- typer.Option(
- "--stops",
- "-x",
- help="Maximum number of stops (ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS)",
- ),
- ] = "ANY",
- monday: Annotated[
- bool,
- typer.Option(
- "--monday",
- "-mon",
- help="Include Mondays in results",
- ),
- ] = False,
- tuesday: Annotated[
- bool,
- typer.Option(
- "--tuesday",
- "-tue",
- help="Include Tuesdays in results",
- ),
- ] = False,
- wednesday: Annotated[
- bool,
- typer.Option(
- "--wednesday",
- "-wed",
- help="Include Wednesdays in results",
- ),
- ] = False,
- thursday: Annotated[
- bool,
- typer.Option(
- "--thursday",
- "-thu",
- help="Include Thursdays in results",
- ),
- ] = False,
- friday: Annotated[
- bool,
- typer.Option(
- "--friday",
- "-fri",
- help="Include Fridays in results",
- ),
- ] = False,
- saturday: Annotated[
- bool,
- typer.Option(
- "--saturday",
- "-sat",
- help="Include Saturdays in results",
- ),
- ] = False,
- sunday: Annotated[
- bool,
- typer.Option(
- "--sunday",
- "-sun",
- help="Include Sundays in results",
- ),
- ] = False,
-):
- """
- Find the cheapest dates to fly between two airports.
-
- Examples:\n
- fli cheap JFK LHR\n
- fli cheap SFO NYC --from 2025-01-01 --to 2025-02-01\n
- fli cheap LAX MIA --seat BUSINESS --stops NON_STOP\n
- fli cheap JFK LHR --monday --friday # Only show Monday and Friday flights\n
- fli cheap SFO NYC --monday --wednesday --friday # Show weekday options
- """
- with console.status("[bold green]Searching for cheapest dates...") as status:
- try:
- # Parse parameters
- departure_airport = getattr(Airport, from_airport.upper())
- arrival_airport = getattr(Airport, to_airport.upper())
- seat_type = getattr(SeatType, seat.upper())
- max_stops = getattr(MaxStops, stops.upper())
-
- # Create flight segment
- flight_segment = FlightSegment(
- departure_airport=[[departure_airport, 0]],
- arrival_airport=[[arrival_airport, 0]],
- travel_date=from_date,
- )
-
- # Create search filters
- filters = DateSearchFilters(
- departure_airport=departure_airport,
- arrival_airport=arrival_airport,
- passenger_info=PassengerInfo(adults=1),
- flight_segments=[flight_segment],
- seat_type=seat_type,
- stops=max_stops,
- from_date=from_date,
- to_date=to_date,
- )
-
- # Perform search
- search_client = SearchDates()
- dates = search_client.search(filters)
-
- if not dates:
- console.print(Panel("No flights found for these dates.", style="red"))
- raise typer.Exit(1)
-
- # Filter by days if any day filters are specified
- selected_days = []
- if monday:
- selected_days.append(DayOfWeek.MONDAY)
- if tuesday:
- selected_days.append(DayOfWeek.TUESDAY)
- if wednesday:
- selected_days.append(DayOfWeek.WEDNESDAY)
- if thursday:
- selected_days.append(DayOfWeek.THURSDAY)
- if friday:
- selected_days.append(DayOfWeek.FRIDAY)
- if saturday:
- selected_days.append(DayOfWeek.SATURDAY)
- if sunday:
- selected_days.append(DayOfWeek.SUNDAY)
-
- dates = filter_dates_by_days(dates, selected_days)
-
- if not dates:
- console.print(Panel("No flights found for the selected days.", style="red"))
- raise typer.Exit(1)
-
- # Display results
- display_date_results(dates)
-
- except (AttributeError, ValueError) as e:
- console.print(f"[red]Error:[/red] {str(e)}")
- raise typer.Exit(1)
-
-
-if __name__ == "__main__":
- cli()
diff --git a/fli/cli/__init__.py b/fli/cli/__init__.py
new file mode 100644
index 0000000..ed85310
--- /dev/null
+++ b/fli/cli/__init__.py
@@ -0,0 +1,5 @@
+"""CLI module for the fli package."""
+
+from fli.cli.main import cli
+
+__all__ = ["cli"]
diff --git a/fli/cli/commands/__init__.py b/fli/cli/commands/__init__.py
new file mode 100644
index 0000000..ffb3b0c
--- /dev/null
+++ b/fli/cli/commands/__init__.py
@@ -0,0 +1,6 @@
+"""Command functions for the CLI."""
+
+from fli.cli.commands.cheap import cheap
+from fli.cli.commands.search import search
+
+__all__ = ["search", "cheap"]
diff --git a/fli/cli/commands/cheap.py b/fli/cli/commands/cheap.py
new file mode 100644
index 0000000..a6196d3
--- /dev/null
+++ b/fli/cli/commands/cheap.py
@@ -0,0 +1,173 @@
+from datetime import datetime, timedelta
+
+import typer
+from typing_extensions import Annotated
+
+from fli.cli.enums import DayOfWeek
+from fli.cli.utils import display_date_results, filter_dates_by_days, validate_date
+from fli.models import (
+ Airport,
+ DateSearchFilters,
+ FlightSegment,
+ MaxStops,
+ PassengerInfo,
+ SeatType,
+)
+from fli.search import SearchDates
+
+
+def cheap(
+ from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
+ to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
+ from_date: Annotated[
+ str, typer.Option("--from", help="Start date (YYYY-MM-DD)", callback=validate_date)
+ ] = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d"),
+ to_date: Annotated[
+ str, typer.Option("--to", help="End date (YYYY-MM-DD)", callback=validate_date)
+ ] = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d"),
+ seat: Annotated[
+ str,
+ typer.Option(
+ "--seat",
+ "-s",
+ help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ ),
+ ] = "ECONOMY",
+ stops: Annotated[
+ str,
+ typer.Option(
+ "--stops",
+ "-x",
+ help="Maximum number of stops (ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS)",
+ ),
+ ] = "ANY",
+ monday: Annotated[
+ bool,
+ typer.Option(
+ "--monday",
+ "-mon",
+ help="Include Mondays in results",
+ ),
+ ] = False,
+ tuesday: Annotated[
+ bool,
+ typer.Option(
+ "--tuesday",
+ "-tue",
+ help="Include Tuesdays in results",
+ ),
+ ] = False,
+ wednesday: Annotated[
+ bool,
+ typer.Option(
+ "--wednesday",
+ "-wed",
+ help="Include Wednesdays in results",
+ ),
+ ] = False,
+ thursday: Annotated[
+ bool,
+ typer.Option(
+ "--thursday",
+ "-thu",
+ help="Include Thursdays in results",
+ ),
+ ] = False,
+ friday: Annotated[
+ bool,
+ typer.Option(
+ "--friday",
+ "-fri",
+ help="Include Fridays in results",
+ ),
+ ] = False,
+ saturday: Annotated[
+ bool,
+ typer.Option(
+ "--saturday",
+ "-sat",
+ help="Include Saturdays in results",
+ ),
+ ] = False,
+ sunday: Annotated[
+ bool,
+ typer.Option(
+ "--sunday",
+ "-sun",
+ help="Include Sundays in results",
+ ),
+ ] = False,
+):
+ """
+ Find the cheapest dates to fly between two airports.
+
+ Examples:\n
+ fli cheap JFK LHR\n
+ fli cheap SFO NYC --from 2025-01-01 --to 2025-02-01\n
+ fli cheap LAX MIA --seat BUSINESS --stops NON_STOP\n
+ fli cheap JFK LHR --monday --friday # Only show Monday and Friday flights\n
+ fli cheap SFO NYC --monday --wednesday --friday # Show weekday options
+ """
+ try:
+ # Parse parameters
+ departure_airport = getattr(Airport, from_airport.upper())
+ arrival_airport = getattr(Airport, to_airport.upper())
+ seat_type = getattr(SeatType, seat.upper())
+ max_stops = getattr(MaxStops, stops.upper())
+
+ # Create flight segment
+ flight_segment = FlightSegment(
+ departure_airport=[[departure_airport, 0]],
+ arrival_airport=[[arrival_airport, 0]],
+ travel_date=from_date,
+ )
+
+ # Create search filters
+ filters = DateSearchFilters(
+ departure_airport=departure_airport,
+ arrival_airport=arrival_airport,
+ passenger_info=PassengerInfo(adults=1),
+ flight_segments=[flight_segment],
+ seat_type=seat_type,
+ stops=max_stops,
+ from_date=from_date,
+ to_date=to_date,
+ )
+
+ # Perform search
+ search_client = SearchDates()
+ dates = search_client.search(filters)
+
+ if not dates:
+ typer.echo("No flights found for these dates.")
+ raise typer.Exit(1)
+
+ # Filter by days if any day filters are specified
+ selected_days = []
+ if monday:
+ selected_days.append(DayOfWeek.MONDAY)
+ if tuesday:
+ selected_days.append(DayOfWeek.TUESDAY)
+ if wednesday:
+ selected_days.append(DayOfWeek.WEDNESDAY)
+ if thursday:
+ selected_days.append(DayOfWeek.THURSDAY)
+ if friday:
+ selected_days.append(DayOfWeek.FRIDAY)
+ if saturday:
+ selected_days.append(DayOfWeek.SATURDAY)
+ if sunday:
+ selected_days.append(DayOfWeek.SUNDAY)
+
+ dates = filter_dates_by_days(dates, selected_days)
+
+ if not dates:
+ typer.echo("No flights found for the selected days.")
+ raise typer.Exit(1)
+
+ # Display results
+ display_date_results(dates)
+
+ except (AttributeError, ValueError) as e:
+ typer.echo(f"Error: {str(e)}")
+ raise typer.Exit(1)
diff --git a/fli/cli/commands/search.py b/fli/cli/commands/search.py
new file mode 100644
index 0000000..5f8f620
--- /dev/null
+++ b/fli/cli/commands/search.py
@@ -0,0 +1,137 @@
+from typing import List, Optional
+
+import typer
+from typing_extensions import Annotated
+
+from fli.cli.utils import (
+ display_flight_results,
+ filter_flights_by_airlines,
+ filter_flights_by_time,
+ parse_airlines,
+ validate_date,
+ validate_time_range,
+)
+from fli.models import Airport, MaxStops, PassengerInfo, SeatType, SortBy
+from fli.search import SearchFlights, SearchFlightsFilters
+
+
+def search_flights(
+ from_airport: str,
+ to_airport: str,
+ date: str,
+ time: Optional[tuple[int, int]] = None,
+ airlines: Optional[List[str]] = None,
+ seat: str = "ECONOMY",
+ stops: str = "ANY",
+ sort: str = "CHEAPEST",
+):
+ """Core flight search functionality."""
+ try:
+ # Parse parameters
+ departure_airport = getattr(Airport, from_airport.upper())
+ arrival_airport = getattr(Airport, to_airport.upper())
+ seat_type = getattr(SeatType, seat.upper())
+ max_stops = getattr(MaxStops, stops.upper())
+ sort_by = getattr(SortBy, sort.upper())
+
+ # Create search filters
+ filters = SearchFlightsFilters(
+ departure_airport=departure_airport,
+ arrival_airport=arrival_airport,
+ departure_date=date,
+ passenger_info=PassengerInfo(adults=1),
+ seat_type=seat_type,
+ stops=max_stops,
+ sort_by=sort_by,
+ )
+
+ # Perform search
+ search_client = SearchFlights()
+ flights = search_client.search(filters)
+
+ if not flights:
+ typer.echo("No flights found.")
+ raise typer.Exit(1)
+
+ # Apply time filter if specified
+ if time:
+ start_hour, end_hour = time
+ flights = filter_flights_by_time(flights, start_hour, end_hour)
+
+ # Apply airline filter if specified
+ airline_list = parse_airlines(airlines)
+ if airline_list:
+ flights = filter_flights_by_airlines(flights, airline_list)
+
+ # Display results
+ display_flight_results(flights)
+
+ except (AttributeError, ValueError) as e:
+ typer.echo(f"Error: {str(e)}")
+ raise typer.Exit(1)
+
+
+def search(
+ from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
+ to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
+ date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)],
+ time: Annotated[
+ Optional[str],
+ typer.Option(
+ "--time",
+ "-t",
+ help="Time range in 24h format (e.g., 6-20)",
+ callback=validate_time_range,
+ ),
+ ] = None,
+ airlines: Annotated[
+ Optional[List[str]],
+ typer.Option(
+ "--airlines",
+ "-a",
+ help="List of airline codes (e.g., BA KL)",
+ ),
+ ] = None,
+ seat: Annotated[
+ str,
+ typer.Option(
+ "--seat",
+ "-s",
+ help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ ),
+ ] = "ECONOMY",
+ stops: Annotated[
+ str,
+ typer.Option(
+ "--stops",
+ "-x",
+ help="Maximum number of stops (ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS)",
+ ),
+ ] = "ANY",
+ sort: Annotated[
+ str,
+ typer.Option(
+ "--sort",
+ "-o",
+ help="Sort results by (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)",
+ ),
+ ] = "CHEAPEST",
+):
+ """
+ Search for flights with flexible filtering options.
+
+ Examples:\n
+ fli search JFK LHR 2025-10-25 --time 6-20 --airlines BA KL\n
+ fli search SFO NYC 2025-11-01 -t 9-17 --stops NON_STOP --sort DURATION\n
+ fli search LAX MIA 2025-12-25 --seat BUSINESS
+ """
+ search_flights(
+ from_airport=from_airport,
+ to_airport=to_airport,
+ date=date,
+ time=time,
+ airlines=airlines,
+ seat=seat,
+ stops=stops,
+ sort=sort,
+ )
diff --git a/fli/cli/console.py b/fli/cli/console.py
new file mode 100644
index 0000000..67f25ff
--- /dev/null
+++ b/fli/cli/console.py
@@ -0,0 +1,5 @@
+"""Console module for the CLI."""
+
+from rich.console import Console
+
+console = Console()
diff --git a/fli/cli/enums.py b/fli/cli/enums.py
new file mode 100644
index 0000000..fc7315c
--- /dev/null
+++ b/fli/cli/enums.py
@@ -0,0 +1,13 @@
+from enum import Enum
+
+
+class DayOfWeek(Enum):
+ """Days of the week."""
+
+ MONDAY = "monday"
+ TUESDAY = "tuesday"
+ WEDNESDAY = "wednesday"
+ THURSDAY = "thursday"
+ FRIDAY = "friday"
+ SATURDAY = "saturday"
+ SUNDAY = "sunday"
diff --git a/fli/cli/main.py b/fli/cli/main.py
new file mode 100644
index 0000000..d6f9b75
--- /dev/null
+++ b/fli/cli/main.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python3
+
+import sys
+
+import typer
+
+from fli.cli.commands.cheap import cheap
+from fli.cli.commands.search import search
+from fli.cli.console import console
+
+app = typer.Typer(
+ help="Search for flights using Google Flights data",
+ add_completion=True,
+)
+
+# Register commands
+app.command(name="search")(search)
+app.command(name="cheap")(cheap)
+
+
[email protected](invoke_without_command=True)
+def main(ctx: typer.Context):
+ """
+ Search for flights using Google Flights data.
+ If no command is provided, the search command will be used.
+ """
+ # If no command is provided, show help
+ if ctx.invoked_subcommand is None:
+ ctx.get_help()
+ raise typer.Exit()
+
+
+def cli():
+ """Entry point for the CLI that handles default command."""
+ args = sys.argv[1:]
+ if not args:
+ app()
+ return
+
+ # If the first argument isn't a command, treat as search
+ if args[0] not in ["search", "cheap", "--help", "-h"]:
+ sys.argv.insert(1, "search")
+
+ app()
+
+
+if __name__ == "__main__":
+ cli()
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
new file mode 100644
index 0000000..5214704
--- /dev/null
+++ b/fli/cli/utils.py
@@ -0,0 +1,174 @@
+from datetime import datetime
+from typing import List, Optional
+
+import typer
+from click import Context, Parameter
+from rich import box
+from rich.console import Group
+from rich.panel import Panel
+from rich.table import Table
+from rich.text import Text
+
+from fli.cli.console import console
+from fli.cli.enums import DayOfWeek
+from fli.models import Airline, Airport
+
+
+def format_airport(airport: Airport) -> str:
+ """Format airport code and name (first two words)."""
+ name_parts = airport.value.split()[:3] # Get first three words
+ name = " ".join(name_parts)
+ return f"{airport.name} ({name})"
+
+
+def validate_time_range(
+ ctx: Context, param: Parameter, value: Optional[str]
+) -> Optional[tuple[int, int]]:
+ """Validate and parse time range in format 'start-end' (24h format)."""
+ if not value:
+ return None
+
+ try:
+ start, end = map(int, value.split("-"))
+ if not (0 <= start <= 23 and 0 <= end <= 23):
+ raise ValueError
+ return start, end
+ except ValueError:
+ raise typer.BadParameter("Time range must be in format 'start-end' (e.g., 6-20)")
+
+
+def validate_date(ctx: Context, param: Parameter, value: str) -> str:
+ """Validate date format."""
+ try:
+ datetime.strptime(value, "%Y-%m-%d")
+ return value
+ except ValueError:
+ raise typer.BadParameter("Date must be in YYYY-MM-DD format")
+
+
+def parse_airlines(airlines: Optional[List[str]]) -> Optional[List[Airline]]:
+ """Parse airlines from list of airline codes."""
+ if not airlines:
+ return None
+
+ try:
+ return [
+ getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()
+ ]
+ except AttributeError as e:
+ raise typer.BadParameter(f"Invalid airline code: {str(e)}")
+
+
+def filter_flights_by_time(flights: list, start_hour: int, end_hour: int) -> list:
+ """Filter flights by departure time range."""
+ return [
+ flight
+ for flight in flights
+ if any(start_hour <= leg.departure_datetime.hour <= end_hour for leg in flight.legs)
+ ]
+
+
+def filter_flights_by_airlines(flights: list, airlines: List[Airline]) -> list:
+ """Filter flights by specified airlines."""
+ return [flight for flight in flights if any(leg.airline in airlines for leg in flight.legs)]
+
+
+def format_duration(minutes: int) -> str:
+ """Format duration in minutes to hours and minutes."""
+ hours = minutes // 60
+ mins = minutes % 60
+ return f"{hours}h {mins}m"
+
+
+def display_flight_results(flights: list):
+ """Display flight results in a beautiful format."""
+ if not flights:
+ console.print(Panel("No flights found matching your criteria", style="red"))
+ return
+
+ for i, flight in enumerate(flights, 1):
+ # Create main flight info table
+ table = Table(show_header=False, box=box.SIMPLE)
+ table.add_column("Label", style="blue")
+ table.add_column("Value", style="green")
+
+ table.add_row("Price", f"${flight.price:,.2f}")
+ table.add_row("Duration", format_duration(flight.duration))
+ table.add_row("Stops", str(flight.stops))
+
+ # Create segments table
+ segments = Table(title="Flight Segments", box=box.ROUNDED)
+ segments.add_column("Airline", style="cyan")
+ segments.add_column("Flight", style="magenta")
+ segments.add_column("From", style="yellow", width=30)
+ segments.add_column("Departure", style="green")
+ segments.add_column("To", style="yellow", width=30)
+ segments.add_column("Arrival", style="green")
+
+ for leg in flight.legs:
+ segments.add_row(
+ leg.airline.value,
+ leg.flight_number,
+ format_airport(leg.departure_airport),
+ leg.departure_datetime.strftime("%H:%M %d-%b"),
+ format_airport(leg.arrival_airport),
+ leg.arrival_datetime.strftime("%H:%M %d-%b"),
+ )
+
+ # Display in a panel
+ console.print(
+ Panel(
+ Group(
+ Text(f"Flight Option {i}", style="bold blue"),
+ Text(""),
+ table,
+ Text(""),
+ segments,
+ ),
+ title=f"[bold]Flight {i} of {len(flights)}[/bold]",
+ border_style="blue",
+ box=box.ROUNDED,
+ )
+ )
+ console.print()
+
+
+def filter_dates_by_days(dates: list, days: List[DayOfWeek]) -> list:
+ """Filter dates by days of the week."""
+ if not days:
+ return dates
+
+ day_numbers = {
+ DayOfWeek.MONDAY: 0,
+ DayOfWeek.TUESDAY: 1,
+ DayOfWeek.WEDNESDAY: 2,
+ DayOfWeek.THURSDAY: 3,
+ DayOfWeek.FRIDAY: 4,
+ DayOfWeek.SATURDAY: 5,
+ DayOfWeek.SUNDAY: 6,
+ }
+
+ allowed_days = {day_numbers[day] for day in days}
+ return [date_price for date_price in dates if date_price.date.weekday() in allowed_days]
+
+
+def display_date_results(dates: list):
+ """Display date search results in a beautiful format."""
+ if not dates:
+ console.print(Panel("No flights found for these dates", style="red"))
+ return
+
+ table = Table(title="Cheapest Dates to Fly", box=box.ROUNDED)
+ table.add_column("Date", style="cyan")
+ table.add_column("Day", style="yellow")
+ table.add_column("Price", style="green")
+
+ for date_price in dates:
+ table.add_row(
+ date_price.date.strftime("%Y-%m-%d"),
+ date_price.date.strftime("%A"),
+ f"${date_price.price:,.2f}",
+ )
+
+ console.print(table)
+ console.print()