import pandas as pd
import pathlib

def read_csv(file_path: pathlib.Path) -> pd.DataFrame:
    """Reads a CSV file into a pandas DataFrame."""
    return pd.read_csv(file_path)

def read_basics(file_path: pathlib.Path) -> pd.Series:
    """Reads first and last row of a CSV file into a pandas Series."""
    df = pd.read_csv(file_path, nrows=1)
    first_row = df.iloc[0]
    data = {
        "file": str(file_path),
        "icao": first_row["icao"],
        "reg": first_row["r"],
        "type": first_row["t"],
        "first_seen": first_row["timestamp"],
        "first_lat": first_row["lat"],
        "first_lon": first_row["lon"],
        "first_alt": first_row["alt"],
        "first_airspeed": first_row["ias"],
    }
    try:
        df_last = pd.read_csv(file_path, skiprows=lambda x: x != 0 and x != sum(1 for _ in open(file_path)) - 1)
        last_row = df_last.iloc[-1]
        data.update({
            "last_seen": last_row["timestamp"],
            "last_lat": last_row["lat"],
            "last_lon": last_row["lon"],
            "last_alt": last_row["alt"],
            "last_airspeed": last_row["ias"],
        })
    except Exception:
        pass
    return pd.Series(data)

def get_basics_from_dir(directory: pathlib.Path, go_into_subdirs: bool = False) -> pd.DataFrame:
    """Aggregates basics from all CSV files in a directory into a DataFrame."""
    all_basics = []
    pattern = "**/*.csv" if go_into_subdirs else "*.csv"
    for csv_file in directory.glob(pattern):
        basics = read_basics(csv_file)
        all_basics.append(basics)
    return pd.DataFrame(all_basics)