#! /usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.13"
# dependencies = [
#     "typer",
#     "selenium",
#     "webdriver-manager",
# ]
# ///

import sys
import json
import typer
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
import time

app = typer.Typer()

def get_destinations(airport_code: str = "BCN") -> str:
    url = f"https://www.flightsfrom.com/{airport_code.upper()}"

    # Set up Selenium with headless Chrome
    chrome_options = Options()
    chrome_options.add_argument("--headless")  # Run in headless mode
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("start-maximized")
    chrome_options.add_argument("disable-infobars")
    chrome_options.add_argument("--disable-extensions")

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)

    try:
        driver.get(url)
        time.sleep(5)  # Wait for the page to load (adjust as needed)

        destinations = []
        elements = driver.find_elements(By.CSS_SELECTOR, "ul.uk-list.uk-list-divider.uk-margin-small-top > li.ff-li-list")

        for li in elements:
            airport_code = li.find_element(By.CSS_SELECTOR, ".ff-row-name a").text.split()[0]
            country = li.find_element(By.CSS_SELECTOR, ".flag-image").get_attribute("uk-tooltip").split(" - ")[0]
            duration = li.find_element(By.CSS_SELECTOR, ".ff-row-duration-mobile .ff-row-text-durationnr").text
            flights_per_day = li.find_element(By.CSS_SELECTOR, ".ff-flights-daily, .ff-flights-daily-desktop").text
            airline = li.find_element(By.CSS_SELECTOR, ".ff-image-airline").get_attribute("alt")
            days = [day.text for day in li.find_elements(By.CSS_SELECTOR, ".flightsfrom-list-days")]
            destinations.append({
                "airport_code": airport_code,
                "country": country,
                "duration": duration,
                "flights_per_day": flights_per_day,
                "airline": airline,
                "days": days
            })

        return json.dumps(destinations, indent=2)
    except Exception as e:
        print(f"Error: {e}")
        return "An error occurred. Check the logs for details."
    finally:
        driver.quit()

@app.command()
def main(airport_code: str = typer.Argument("BCN", help="The airport code to fetch destinations for (default: BCN).")):
    """
    Get flight destinations from a specific airport.
    """
    print(get_destinations(airport_code))

if __name__ == "__main__":
    app()
