import { exec } from "child_process";
import { promisify } from "util";
import log from "electron-log/main";

const execPromise = promisify(exec);

// Define the interval as a variable (in minutes)
const KEEP_ALIVE_INTERVAL_MINUTES = 15;

export async function setupKeepAliveTask(): Promise<void> {
  const taskName = "ImEXShopPartnerKeepAlive";
  const protocolUrl = "imexmedia://keep-alive";
  // Use rundll32.exe to silently open the URL as a protocol
  const command = `rundll32.exe url.dll,OpenURL "${protocolUrl}"`;
  // Escape quotes for schtasks /tr parameter
  const escapedCommand = command.replace(/"/g, '\\"');

  const schtasksCommand = `schtasks /create /tn "${taskName}" /tr "${escapedCommand}" /sc minute /mo ${KEEP_ALIVE_INTERVAL_MINUTES} /f`;

  try {
    const { stdout, stderr } = await execPromise(schtasksCommand);
    log.info(`Scheduled task created: ${stdout}`);
    if (stderr) log.warn(`Scheduled task stderr: ${stderr}`);
  } catch (error) {
    log.error(
      `Error creating scheduled task: ${error instanceof Error ? error.message : String(error)}`,
    );
    throw error; // Rethrow to allow caller to handle
  }
}

export async function isKeepAliveTaskInstalled(): Promise<boolean> {
  const taskName = "ImEXShopPartnerKeepAlive";
  const maxRetries = 3;
  const retryDelay = 500; // 500ms delay between retries

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const { stdout } = await execPromise(`schtasks /query /tn "${taskName}"`);
      return !!stdout; // Return true if task exists
    } catch (error) {
      log.debug(
        `Scheduled task ${taskName} not found (attempt ${attempt}/${maxRetries}): ${error instanceof Error ? error.message : String(error)}`,
      );
      if (attempt === maxRetries) {
        return false; // Return false after all retries fail
      }
      // Wait before retrying
      await new Promise((resolve) => setTimeout(resolve, retryDelay));
    }
  }
  return false; // Fallback return
}
