// /utils/loadWindowVariables.ts

interface CustomWindow extends Window {
  [key: string]: any;
}

export async function loadWindowVariables(): Promise<{
  variables: Record<string, any>;
  kueData?: Record<string, any>;
}> {
  return new Promise((resolve, reject) => {
    const requiredVars: string[] = ["win_deviceName"];
    const isDev = window.location.hostname === "localhost";
    const pathname = window.location.pathname;

    const scripts: string[] = [];

    if (pathname.includes("kabelueberwachung")) {
      scripts.push(isDev ? "kabelueberwachungAPIHandler" : "kueData.js");
    } else if (pathname.includes("digitalInputs")) {
      scripts.push(isDev ? "getDigitalInputsHandler" : "digitalInputs.js");
    } else if (pathname.includes("digitalOutputs")) {
      scripts.push(isDev ? "digitalOutputsAPIHandler" : "digitalOutputs.js");
    } else if (pathname.includes("analogInputs")) {
      scripts.push(isDev ? "getAnalogInputsHandler" : "analogInputs.js");
    } else if (pathname.includes("dashboard")) {
      scripts.push(
        isDev ? "last20MessagesAPIHandler" : "start.js",
        isDev ? "opcuaAPIHandler" : "opcua.js"
      );
    } else if (pathname.includes("einstellungen")) {
      scripts.push(isDev ? "opcuaAPIHandler" : "opcua.js");
    }

    scripts.push(isDev ? "systemAPIHandler" : "system.js");

    const loadScript = (src: string): Promise<void> => {
      return new Promise((resolve, reject) => {
        const script = document.createElement("script");
        script.src = isDev ? `/api/cpl/${src}` : `/CPL?/CPL/SERVICE/${src}`;
        script.async = true;
        script.onload = () => resolve();
        script.onerror = () => reject(new Error(`Script load error: ${src}`));
        document.head.appendChild(script);
      });
    };

    scripts
      .reduce(
        (promise, script) => promise.then(() => loadScript(script)),
        Promise.resolve()
      )
      .then(() => {
        const win = window as unknown as CustomWindow;

        const variablesObj: Record<string, any> = requiredVars.reduce(
          (acc: Record<string, any>, variable: string) => {
            if (win[variable] !== undefined) {
              acc[variable.replace("win_", "")] = win[variable];
            }
            return acc;
          },
          {} as Record<string, any>
        );

        const kueData =
          pathname.includes("kabelueberwachung") && typeof win === "object"
            ? {
                kueOnline: win.win_kueOnline || [],
                kueID: win.win_kueID || [],
                kueName: win.win_kueName || [],
                kuePSTmMinus96V: win.win_kuePSTmMinus96V || [],
                kueAlarm1: win.win_kueAlarm1 || [],
                kueAlarm2: win.win_kueAlarm2 || [],
                kueIso: win.win_kueIso || [],
                kueResidence: win.win_kueResidence || [],
                kueCableBreak: win.win_kueCableBreak || [],
                kueGroundFault: win.win_kueGroundFault || [],
                kueLimit1: win.win_kueLimit1 || [],
                kueLimit2Low: win.win_kueLimit2Low || [],
                kueDelay1: win.win_kueDelay1 || [],
                kueLoopInterval: win.win_kueLoopInterval || [],
                kueVersion: win.win_kueVersion || [],
                kueOverflow: win.win_kueOverflow || [],
                tdrAtten: win.win_tdrAtten || [],
                tdrPulse: win.win_tdrPulse || [],
                tdrSpeed: win.win_tdrSpeed || [],
                tdrAmp: win.win_tdrAmp || [],
                tdrTrigger: win.win_tdrTrigger || [],
                tdrLocation: win.win_tdrLocation || [],
                tdrActive: win.win_tdrActive || [],
                tdrLast: win.win_tdrLast || [],
                tdrOverflow: win.win_kueOverflow || [],
                memoryInterval: win.win_memoryInterval || [],
              }
            : undefined;

        resolve({ variables: variablesObj, kueData });
      })
      .catch((error) => {
        console.error("❌ Fehler beim Laden eines Skripts:", error);
        reject(error);
      });
  });
}
