import log from 'electron-log';
import { execAsync } from '../utils/shell-utils';
import { isNewerVersion } from '../utils/version-utils';

export interface HomebrewStatus {
  installed: boolean;
  version: string | null;
  path: string | null;
  updateAvailable: boolean;
  latestVersion: string | null;
}

const COMMAND_TIMEOUT = 5000;

async function execWithTimeout(
  command: string,
  timeoutMs: number = COMMAND_TIMEOUT
): Promise<{ stdout: string; stderr: string }> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const result = await execAsync(command, { signal: controller.signal });
    clearTimeout(timeout);
    return result;
  } catch (error: any) {
    clearTimeout(timeout);
    if (error.name === 'AbortError') {
      throw new Error(`Command timed out after ${timeoutMs}ms: ${command}`);
    }
    throw error;
  }
}

export async function checkHomebrewStatus(): Promise<HomebrewStatus> {
  const status: HomebrewStatus = {
    installed: false,
    version: null,
    path: null,
    updateAvailable: false,
    latestVersion: null
  };

  // Check both Intel and Apple Silicon paths
  const brewPaths = ['/opt/homebrew/bin/brew', '/usr/local/bin/brew'];

  for (const brewPath of brewPaths) {
    try {
      await execWithTimeout(`test -f ${brewPath}`);
      status.installed = true;
      status.path = brewPath;

      // Get Homebrew version
      try {
        const versionResult = await execWithTimeout(`${brewPath} --version`);
        const versionMatch = versionResult.stdout.match(/Homebrew ([\d.]+)/);
        if (versionMatch) {
          status.version = versionMatch[1];
        }
      } catch (error) {
        log.warn('Failed to get Homebrew version:', error);
      }

      // Check for updates by fetching the latest release from GitHub
      if (status.version) {
        try {
          const apiUrl = 'https://api.github.com/repos/Homebrew/brew/releases/latest';
          const curlResult = await execWithTimeout(
            `curl -s "${apiUrl}" | grep -oE '"tag_name": "[0-9.]+"' | head -1 | cut -d'"' -f4`,
            10000
          );

          const latestVersion = curlResult.stdout.trim();

          if (latestVersion && /^\d+\.\d+\.\d+$/.test(latestVersion)) {
            status.latestVersion = latestVersion;
            log.info(`Found latest Homebrew version: ${latestVersion}, current: ${status.version}`);

            // Compare versions
            if (isNewerVersion(status.version, latestVersion)) {
              status.updateAvailable = true;
              log.info(`Homebrew update available: ${status.version} -> ${latestVersion}`);
            } else {
              status.updateAvailable = false;
              log.info('Homebrew is up to date');
            }
          } else {
            log.warn('Could not parse version from Homebrew GitHub API');
          }
        } catch (error) {
          log.info('Could not check for Homebrew updates:', error);
        }
      }

      break;
    } catch (error) {
      continue;
    }
  }

  if (!status.installed) {
    log.info('Homebrew is not installed');
  }

  return status;
}
