export interface DigitalInput {
  id: number;
  value: number | string;
  label: string;
  invert: boolean;
  counter: number | string;
  timeFilter: number | string;
  weighting: number | string;
  counterActive: boolean;
  eingangOffline: boolean;
  status: boolean;
  flutter: boolean;
  zaehlerAktiv: boolean;
}

// 🧠 Neu: CSV-Zeile wie "1,0,1,0" in [1,0,1,0] konvertieren
const parseCsvNumbers = (line: string): number[] =>
  line.split(",").map((v) => Number(v.trim()));

// 🧠 Neu: CSV-Zeile wie "'DE1','DE2'" in ["DE1", "DE2"] umwandeln
const parseCsvLabels = (line: string): string[] =>
  line.split(",").map((v) => v.trim().replace(/^'+|'+$/g, ""));

export const fetchDigitalInputsService = async (): Promise<DigitalInput[]> => {
  const hostname = window.location.hostname;
  const mode =
    hostname === "localhost" || hostname === "127.0.0.1" ? "dev" : "production";

  const url =
    mode === "production"
      ? "/CPL?/CPL/SERVICE/digitalInputs.json"
      : "/api/cpl/getDigitalInputsHandler";

  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`❌ Fehler beim Laden der digitalen Eingänge (${mode})`);
  }

  const data = await res.json();

  // 🧠 Neu: CSV-Zeilen in Arrays umwandeln
  const state = data.win_de_state.flatMap(parseCsvNumbers);
  const label = data.win_de_label.flatMap(parseCsvLabels);
  const invert = data.win_de_invert.flatMap(parseCsvNumbers);
  const counter = data.win_de_counter.flatMap((line: string) =>
    line.split(",").map((v) => v.trim())
  );
  const timeFilter = data.win_de_time_filter.flatMap((line: string) =>
    line.split(",").map((v) => v.trim())
  );
  const weighting = data.win_de_weighting.flatMap((line: string) =>
    line.split(",").map((v) => v.trim())
  );
  const counterActive = data.win_de_counter_active.flatMap(parseCsvNumbers);
  const offline = data.win_de_offline.flatMap(parseCsvNumbers);

  interface CsvData {
    state: number[];
    label: string[];
    invert: number[];
    counter: (number | string)[];
    timeFilter: (number | string)[];
    weighting: (number | string)[];
    counterActive: number[];
    offline: number[];
  }

  // Removed redundant DigitalInputResult interface

  const csvData: CsvData = {
    state,
    label,
    invert,
    counter,
    timeFilter,
    weighting,
    counterActive,
    offline,
  };

  return csvData.state.map(
    (_, i): DigitalInput => ({
      id: i + 1,
      value: csvData.state[i],
      label: csvData.label[i],
      invert: !!csvData.invert[i],
      counter: csvData.counter[i],
      timeFilter: csvData.timeFilter[i],
      weighting: csvData.weighting[i],
      counterActive: !!csvData.counterActive[i],
      eingangOffline: !!csvData.offline[i],
      status: !!csvData.state[i],
      flutter: false,
      zaehlerAktiv: false,
    })
  );
};
