import { isInExpectedZone, isStale, newestTelematicsTimestamp } from "@/lib/fleet/geo";
import type {
  ReadinessIssue,
  ReadinessResult,
  Site,
  VehicleMaster,
  WarningLevel,
} from "@/lib/fleet/types";

export const READINESS_THRESHOLDS = {
  minBatteryPct: 40,
  minFuelPct: 35,
  staleMinutes: 120,
} as const;

function isWarning(level: WarningLevel): boolean {
  return level === "WARNING" || level === "CRITICAL";
}

function exteriorOpen(vehicle: VehicleMaster): string[] {
  const e = vehicle.exterior;
  const checks: { open: boolean; label: string }[] = [
    { open: e.frontLeftDoor === "OPEN", label: "Fahrertür" },
    { open: e.frontRightDoor === "OPEN", label: "Beifahrertür" },
    { open: e.rearLeftDoor === "OPEN", label: "Tür hinten links" },
    { open: e.rearRightDoor === "OPEN", label: "Tür hinten rechts" },
    { open: e.frontLeftWindow === "OPEN", label: "Fenster vorne links" },
    { open: e.frontRightWindow === "OPEN", label: "Fenster vorne rechts" },
    { open: e.rearLeftWindow === "OPEN", label: "Fenster hinten links" },
    { open: e.rearRightWindow === "OPEN", label: "Fenster hinten rechts" },
    { open: e.hood === "OPEN", label: "Motorhaube" },
    { open: e.tailgate === "OPEN", label: "Heckklappe" },
    { open: e.tankLid === "OPEN", label: "Tankdeckel" },
    { open: e.sunroof === "OPEN", label: "Schiebedach" },
  ];
  const open = checks.filter((c) => c.open).map((c) => c.label);
  if (e.centralLock === "UNLOCKED") open.push("Zentralverriegelung offen");
  return open;
}

function healthIssues(vehicle: VehicleMaster): string[] {
  const h = vehicle.health;
  const out: string[] = [];
  if (isWarning(h.serviceWarning)) out.push("Servicehinweis");
  if (isWarning(h.brakeFluidLevelWarning)) out.push("Bremsflüssigkeit");
  if (isWarning(h.engineCoolantLevelWarning)) out.push("Kühlmittel");
  if (isWarning(h.oilLevelWarning)) out.push("Ölstand");
  if (isWarning(h.lowVoltageBatteryWarning)) out.push("12-V-Batterie");
  if (isWarning(h.frontLeftTyrePressureWarning)) out.push("Reifen VL");
  if (isWarning(h.frontRightTyrePressureWarning)) out.push("Reifen VR");
  if (isWarning(h.rearLeftTyrePressureWarning)) out.push("Reifen HL");
  if (isWarning(h.rearRightTyrePressureWarning)) out.push("Reifen HR");
  return out;
}

export function evaluateReadiness(
  vehicle: VehicleMaster,
  sites: Site[],
  now = Date.now(),
): ReadinessResult {
  const issues: ReadinessIssue[] = [];

  if (vehicle.availability.availabilityStatus === "UNAVAILABLE") {
    issues.push({
      code: "UNAVAILABLE",
      message: vehicle.availability.unavailableReason
        ? `Nicht verfügbar (${vehicle.availability.unavailableReason})`
        : "Fahrzeug nicht verfügbar",
      severity: "critical",
    });
  }

  const stamp = newestTelematicsTimestamp(vehicle);
  if (isStale(stamp, READINESS_THRESHOLDS.staleMinutes, now)) {
    issues.push({
      code: "STALE_DATA",
      message: "Telematikdaten veraltet – kein verlässlicher Check möglich",
      severity: "critical",
    });
  }

  if (vehicle.battery) {
    if (
      vehicle.battery.batteryChargeLevelPercentage <
      READINESS_THRESHOLDS.minBatteryPct
    ) {
      issues.push({
        code: "LOW_ENERGY",
        message: `Batterie unter ${READINESS_THRESHOLDS.minBatteryPct}% (${vehicle.battery.batteryChargeLevelPercentage}%)`,
        severity: "warning",
      });
    }
  } else if (vehicle.fuel) {
    if (vehicle.fuel.fuelLeftPercentage < READINESS_THRESHOLDS.minFuelPct) {
      issues.push({
        code: "LOW_ENERGY",
        message: `Tank unter ${READINESS_THRESHOLDS.minFuelPct}% (${vehicle.fuel.fuelLeftPercentage}%)`,
        severity: "warning",
      });
    }
  }

  const openParts = exteriorOpen(vehicle);
  if (openParts.length) {
    issues.push({
      code: "EXTERIOR_OPEN",
      message: `Offen: ${openParts.join(", ")}`,
      severity: "warning",
    });
  }

  const health = healthIssues(vehicle);
  if (health.length) {
    issues.push({
      code: "HEALTH_WARNING",
      message: `Warnungen: ${health.join(", ")}`,
      severity: "critical",
    });
  }

  const sw = vehicle.carInformation;
  if (
    sw.currentCarSoftwareVersion !== sw.latestAvailableCarSoftwareVersion
  ) {
    issues.push({
      code: "SOFTWARE_OUTDATED",
      message: `Software ${sw.currentCarSoftwareVersion} → verfügbar ${sw.latestAvailableCarSoftwareVersion}`,
      severity: "info",
    });
  }

  if (!isInExpectedZone(vehicle, sites) && !isStale(stamp, READINESS_THRESHOLDS.staleMinutes, now)) {
    issues.push({
      code: "LOCATION_MISMATCH",
      message: "Standort weicht von erwarteter Zone ab",
      severity: "info",
    });
  }

  const blocking = issues.filter((i) => i.severity !== "info");
  const ready = blocking.length === 0;
  const score = Math.max(0, 100 - blocking.length * 18 - (issues.length - blocking.length) * 5);

  return { vin: vehicle.vin, ready, score, issues };
}
