import {
  findZoneForVehicle,
  isInExpectedZone,
  isStale,
  newestTelematicsTimestamp,
  ZONE_LABELS,
} from "@/lib/fleet/geo";
import type {
  EveningCheckResult,
  EveningIssue,
  Site,
  VehicleMaster,
  WarningLevel,
} from "@/lib/fleet/types";

export const EVENING_THRESHOLDS = {
  staleMinutes: 180,
  criticalBatteryPct: 20,
  criticalFuelPct: 15,
} as const;

function isCritical(level: WarningLevel): boolean {
  return level === "CRITICAL";
}

function hasOpenExterior(vehicle: VehicleMaster): string[] {
  const e = vehicle.exterior;
  const labels: [keyof typeof e, string][] = [
    ["frontLeftDoor", "Fahrertür"],
    ["frontRightDoor", "Beifahrertür"],
    ["rearLeftDoor", "Tür HL"],
    ["rearRightDoor", "Tür HR"],
    ["frontLeftWindow", "Fenster VL"],
    ["frontRightWindow", "Fenster VR"],
    ["rearLeftWindow", "Fenster HL"],
    ["rearRightWindow", "Fenster HR"],
    ["hood", "Haube"],
    ["tailgate", "Heckklappe"],
  ];
  return labels
    .filter(([k]) => e[k] === "OPEN")
    .map(([, label]) => label);
}

export function evaluateEveningCheck(
  vehicle: VehicleMaster,
  sites: Site[],
  now = Date.now(),
): EveningCheckResult {
  const issues: EveningIssue[] = [];
  const stamp = newestTelematicsTimestamp(vehicle);
  const locationStale = isStale(
    vehicle.location.properties.timestamp,
    EVENING_THRESHOLDS.staleMinutes,
    now,
  );
  const dataStale = isStale(stamp, EVENING_THRESHOLDS.staleMinutes, now);

  if (dataStale) {
    issues.push({
      code: "STALE_DATA",
      message: "Fahrzeugdaten älter als erlaubter Aktualitätswert",
      severity: "warning",
    });
  }

  if (!locationStale && !isInExpectedZone(vehicle, sites)) {
    const actual = findZoneForVehicle(vehicle, sites);
    const expectedSite = sites.find((s) => s.id === vehicle.expectedSiteId);
    const expectedLabel = `${expectedSite?.shortName ?? vehicle.expectedSiteId} / ${ZONE_LABELS[vehicle.expectedZoneId]}`;
    const actualLabel = actual
      ? `${sites.find((s) => s.id === actual.siteId)?.shortName} / ${ZONE_LABELS[actual.id]}`
      : "außerhalb bekannter Zonen";
    issues.push({
      code: "ZONE_MISMATCH",
      message: `Erwartet ${expectedLabel}, aktuell ${actualLabel}`,
      severity: "warning",
    });
  }

  const open = hasOpenExterior(vehicle);
  if (open.length) {
    issues.push({
      code: "EXTERIOR_OPEN",
      message: `Offen: ${open.join(", ")}`,
      severity: "critical",
    });
  }

  if (vehicle.exterior.centralLock === "UNLOCKED") {
    issues.push({
      code: "UNLOCKED",
      message: "Zentralverriegelung nicht verriegelt",
      severity: "critical",
    });
  }

  if (vehicle.battery) {
    const b = vehicle.battery;
    if (
      b.batteryChargeLevelPercentage < EVENING_THRESHOLDS.criticalBatteryPct ||
      b.chargingStatus === "ERROR" ||
      b.chargerConnectionStatus === "FAULT"
    ) {
      issues.push({
        code: "CRITICAL_ENERGY",
        message: `Energie kritisch (SoC ${b.batteryChargeLevelPercentage}%, Status ${b.chargingStatus})`,
        severity: "critical",
      });
    }
  } else if (vehicle.fuel) {
    if (vehicle.fuel.fuelLeftPercentage < EVENING_THRESHOLDS.criticalFuelPct) {
      issues.push({
        code: "CRITICAL_ENERGY",
        message: `Tank kritisch (${vehicle.fuel.fuelLeftPercentage}%)`,
        severity: "critical",
      });
    }
  }

  const h = vehicle.health;
  const criticalHealth =
    isCritical(h.lowVoltageBatteryWarning) ||
    isCritical(h.brakeFluidLevelWarning) ||
    isCritical(h.engineCoolantLevelWarning) ||
    isCritical(h.oilLevelWarning);

  if (criticalHealth) {
    issues.push({
      code: "CRITICAL_HEALTH",
      message: "Kritische Health-Warnung vor dem nächsten Betriebstag",
      severity: "critical",
    });
  }

  return {
    vin: vehicle.vin,
    issues,
    attentionNeeded: issues.length > 0,
  };
}
