import csv
import re
import requests
from datetime import datetime
from typing import List, Optional

# Timestamps from AbflugClient / aircraft_status (naive local wall clock, consistent for duration math)
LEDGER_DT_FORMAT = "%Y-%m-%d %H:%M:%S"


def ledger_column_names() -> List[str]:
    return ["departure", "arrival", "aircraft", "duration", "date", "flight_number"]


def sanitize_aircraft_token(model: Optional[str]) -> str:
    if not model or not str(model).strip():
        return ""
    return str(model).strip().lower()


def ledger_duration_hh_mm(departure_time: str, arrival_time: str) -> str:
    if not departure_time or not str(departure_time).strip():
        return "0:00"
    if not arrival_time or not str(arrival_time).strip():
        return "0:00"
    try:
        t0 = datetime.strptime(str(departure_time).strip(), LEDGER_DT_FORMAT)
        t1 = datetime.strptime(str(arrival_time).strip(), LEDGER_DT_FORMAT)
    except (ValueError, TypeError):
        return "0:00"
    total_minutes = max(0, int((t1 - t0).total_seconds() // 60))
    h, m = divmod(total_minutes, 60)
    return f"{h}:{m:02d}"


def ledger_date_from_arrival(arrival_time: str) -> str:
    if not arrival_time or not str(arrival_time).strip():
        return datetime.now().strftime("%Y-%m-%d")
    try:
        dt = datetime.strptime(str(arrival_time).strip(), LEDGER_DT_FORMAT)
        return dt.strftime("%Y-%m-%d")
    except (ValueError, TypeError):
        return datetime.now().strftime("%Y-%m-%d")


def build_ledger_csv_row(
    departure_airport: str,
    arrival_airport: str,
    aircraft_token: str,
    departure_time: str,
    arrival_time: str,
    flight_number: str,
) -> List[str]:
    return [
        departure_airport or "",
        arrival_airport or "",
        aircraft_token or "",
        ledger_duration_hh_mm(departure_time, arrival_time),
        ledger_date_from_arrival(arrival_time),
        flight_number or "",
    ]


def sanitize_ledger_filename_token(code: str) -> str:
    if not code:
        return "XXXX"
    s = str(code).strip().upper()
    s = re.sub(r"[^A-Z0-9]", "", s)
    return (s[:4] or "XXXX")


def ledger_final_basename(departure_icao: str, arrival_icao: str, land_utc: datetime) -> str:
    dep = sanitize_ledger_filename_token(departure_icao)
    arr = sanitize_ledger_filename_token(arrival_icao)
    d = land_utc.strftime("%Y-%m-%d_%H%M%S")
    return f"AviatorLedger_{dep}_{arr}_{d}.csv"


def write_ledger_csv_line(file_handle, columns: List[str]) -> None:
    writer = csv.writer(file_handle, lineterminator="\n")
    writer.writerow(columns)


def prepare_flight_data_for_discord(flight_number, departure_airport, arrival_airport, departure_time, arrival_time, pilot,action="",gate="",runway=""):
    current_time = datetime.now().strftime("%H:%M")
    # Initialize content to None to catch any missing cases
    content = None
    
    if action == "departing":
        # Handle departure_time - might be empty string or None
        if departure_time and departure_time.strip():
            try:
                dep_time_str = datetime.strptime(departure_time, "%Y-%m-%d %H:%M:%S").strftime("%H:%M")
            except (ValueError, TypeError):
                dep_time_str = datetime.now().strftime("%H:%M")
        else:
            dep_time_str = datetime.now().strftime("%H:%M")
        content = f"Taking off from {departure_airport} → {arrival_airport} at {dep_time_str} from runway {runway}"
    elif action == "landed":
        # Handle arrival_time - might be empty string or None
        if arrival_time and arrival_time.strip():
            try:
                arr_time_str = datetime.strptime(arrival_time, "%Y-%m-%d %H:%M:%S").strftime("%H:%M")
            except (ValueError, TypeError):
                arr_time_str = datetime.now().strftime("%H:%M")
        else:
            arr_time_str = datetime.now().strftime("%H:%M")
        content = f"Landed at {arrival_airport} from {departure_airport} at {arr_time_str} on runway {runway}"
    elif action == "in flight":
        # Handle departure_time - might be empty string or None
        if departure_time and departure_time.strip():
            try:
                dep_time_str = datetime.strptime(departure_time, "%Y-%m-%d %H:%M:%S").strftime("%H:%M")
            except (ValueError, TypeError):
                dep_time_str = datetime.now().strftime("%H:%M")
        else:
            dep_time_str = datetime.now().strftime("%H:%M")
        content = f"In flight from {departure_airport} to {arrival_airport} runway {runway} since {dep_time_str} from gate {gate}"
    elif action == "taxiing":
        content = f"Taxiing at {departure_airport} from gate {gate} to runway {runway}"
    
    # Return None if action is invalid or content wasn't set
    if content is None:
        return None
    
    return {
        "content": content,
        "embeds": [
            {
                "title": f"Flight {flight_number}",
                "description": content,
                "color": get_color_code("Aqua")
            }
        ]
    }
def get_color_code(color_name):
    if color_name == "Default":
        return 0
    elif color_name == "Aqua":
        return 1752220
    elif color_name == "DarkAqua":
        return 1146986
    elif color_name == "Green":
        return 5763719
    elif color_name == "DarkGreen":
        return 2067276
    elif color_name == "Blue":
        return 3447003
    elif color_name == "DarkBlue":
        return 2123412
    elif color_name == "Purple":
        return 10181046
    elif color_name == "DarkPurple":
        return 7419530
    elif color_name == "LuminousVividPink":
        return 15277667
    elif color_name == "DarkVividPink":
        return 11342935
    elif color_name == "Gold":
        return 15844367
    elif color_name == "DarkGold":
        return 12745742
    elif color_name == "Orange":
        return 15105570
    elif color_name == "DarkOrange":
        return 11027200
    elif color_name == "Red":
        return 15548997
    elif color_name == "DarkRed":
        return 10038562
    elif color_name == "Grey":
        return 9807270
    elif color_name == "DarkGrey":
        return 9936031
    elif color_name == "DarkerGrey":
        return 8359053
    elif color_name == "LightGrey":
        return 12370112
    elif color_name == "Navy":
        return 3426654
    elif color_name == "DarkNavy":
        return 2899536
    elif color_name == "Yellow":
        return 16776960
    else:
        return 0

if __name__ == "__main__":
    pass