#version = 1.0
msfs_mode = 1

HANDLING_BY_AIRLINE = {
	"AEE": "CELEBI",
	"BTI": "CELEBI",
	"AUA": "CELEBI",
	"BEL": "CELEBI",
	"ELY": "CELEBI",
	"EWG": "CELEBI",
	"EWL": "CELEBI",
	"FDB": "CELEBI",
	"DLH": "CELEBI",
	"GEC": "CELEBI",
	"LHX": "CELEBI",
	"CLH": "CELEBI",
	"PGT": "CELEBI",
	"QTR": "CELEBI",
	"RYR": "CELEBI",
	"RUK": "CELEBI",
	"SXS": "CELEBI",
	"SWR": "CELEBI",
	"THY": "CELEBI",
	"EIN": "MENZ",
	"EUK": "MENZ",
	"CCA": "MENZ",
	"AFR": "MENZ",
	"HOP": "MENZ",
	"CES": "MENZ",
	"EZY": "MENZ",
	"EJU": "MENZ",
	"EZS": "MENZ",
	"MSR": "MENZ",
	"MSX": "MENZ",
	"UAE": "MENZ",
	"FIN": "MENZ",
	"IBE": "MENZ",
	"IBS": "MENZ",
	"EXS": "MENZ",
	"KLM": "MENZ",
	"KLC": "MENZ",
	"KAL": "MENZ",
	"LOT": "MENZ",
	"NOZ": "MENZ",
	"NSZ": "MENZ",
	"ROT": "MENZ",
	"WZZ": "MENZ",
	"WAZ": "MENZ",
	"WMT": "MENZ",
	"WUK": "MENZ",
	"BAW": "MENZ",
	"SHT": "MENZ",
	"SAS": "MENZ",
}

HANDLING_FALLBACK = "MENZ,CELEBI"
CATERING_TEXTURE = "GGOURMET"

STAIRS_BOOST = 10
TRACTOR_BOOST = 10

_GATE_DISTANCE_THRESHOLD_METERS = 25


def _contains(text, needle):
	return needle.lower() in (text or "").lower()


def _get_airline_code():
	try:
		sb = getSimbrief()
	except Exception:
		sb = None

	code = getattr(sb, "icao_airline", None)
	if code:
		return str(code).upper().strip()

	gate = getGate()
	if gate:
		for attr_name in ("airlineCode", "airline", "icao_airline"):
			value = getattr(gate, attr_name, None)
			if value:
				return str(value).upper().strip()

	return ""


def _apply_gate_distance_threshold():
	if _GATE_DISTANCE_THRESHOLD_METERS is None:
		return

	gate = getGate()
	if not gate:
		return

	try:
		d = Distance.fromMeters(_GATE_DISTANCE_THRESHOLD_METERS)
	except Exception:
		return

	try:
		gate.__setattr__("gateDistanceThreshold", d)
	except Exception:
		pass


def onAirportBeforeVehicleSelect(self):
	gate = getGate()
	if not gate:
		return

	airline = _get_airline_code()
	gate.handlingTexture = HANDLING_BY_AIRLINE.get(airline, HANDLING_FALLBACK)
	gate.cateringTexture = CATERING_TEXTURE
	_apply_gate_distance_threshold()


def onAirportVehicleCandidatesScored(self, vehicleType, candidates):
	for c in candidates:
		title = getattr(c, "title", "") or ""
		model_name = getattr(c, "modelName", "") or ""
		texture = getattr(c, "texture", "") or ""
		search_blob = f"{title} {model_name} {texture}"

		if vehicleType == "Staircase" and _contains(search_blob, "CDS"):
			c.boostScore(STAIRS_BOOST)

		if vehicleType == "BaggageTractor" and _contains(search_blob, "Endurance"):
			c.boostScore(TRACTOR_BOOST)
