// ✅ Service: /services/fetchAnalogeEingaenge.ts

export const fetchAnalogeEingaenge = async () => {
  try {
    if (typeof window === "undefined") return null;

    // ✅ Pfad je nach Umgebung
    const scriptSrc =
      process.env.NODE_ENV === "production"
        ? "/CPL?/CPL/SERVICE/ae.js"
        : "/CPLmockData/SERVICE/ae.js";

    await new Promise<void>((resolve, reject) => {
      const script = document.createElement("script");
      script.src = scriptSrc;
      script.async = true;
      script.onload = () => resolve();
      script.onerror = () => reject("❌ Fehler beim Laden von ae.js");
      document.body.appendChild(script);
    });

    const formattedData: Record<string, any> = {};
    for (let i = 1; i <= 8; i++) {
      const varName = `win_analogeEingaenge${i}`;
      const raw = (window as any)[varName];
      if (raw && Array.isArray(raw)) {
        formattedData[varName] = {
          id: raw[0],
          value: raw[1],
          name: raw[2],
          uW: raw[3] === 1,
          uG: raw[4] === 1,
          oW: raw[5] === 1,
          oG: raw[6] === 1,
        };
      }
    }

    return formattedData;
  } catch (error) {
    console.error("❌ Fehler beim Laden der analogen Eingänge:", error);
    return null;
  }
};
