/* eslint global-require: off, no-console: off, promise/always-return: off */

/**
 * This module executes inside of electron's main process. You can start
 * electron renderer process from here and communicate with the other processes
 * through IPC.
 *
 * When running `npm run build` or `npm run build:main`, this file is compiled to
 * `./src/main.js` using webpack. This gives us some performance wins.
 */
import path from 'path';
import { app, BrowserWindow, shell, ipcMain, dialog } from 'electron';
import { autoUpdater } from 'electron-updater';
import { exec, spawn } from 'child_process';
import { promisify } from 'util';
import log from 'electron-log';
import fs from 'fs/promises';
import MenuBuilder from './menu';
import { resolveHtmlPath } from './util';

const execAsync = promisify(exec);

// Helper function para construir comando kubectl com kubeconfig
const buildKubectlCommand = async (
  baseCommand: string,
  kubeconfig?: string,
): Promise<string> => {
  let command = baseCommand;

  if (kubeconfig && kubeconfig.trim() !== '') {
    let expandedKubeconfig = kubeconfig;

    // Expandir ~ para home directory
    if (kubeconfig.startsWith('~')) {
      expandedKubeconfig = kubeconfig.replace('~', require('os').homedir());
    }
    // Se não for caminho absoluto, considerar relativo ao diretório do app
    else if (!path.isAbsolute(kubeconfig)) {
      // Tentar primeiro no diretório atual
      expandedKubeconfig = path.join(process.cwd(), kubeconfig);

      // Se não existir, tentar no diretório home do usuário
      try {
        await require('fs').promises.access(expandedKubeconfig);
      } catch {
        expandedKubeconfig = path.join(require('os').homedir(), kubeconfig);
      }
    }

    try {
      await require('fs').promises.access(expandedKubeconfig);
      // Arquivo existe, adicionar ao comando
      if (!baseCommand.includes('--kubeconfig')) {
        command = baseCommand.replace(
          'kubectl',
          `kubectl --kubeconfig="${expandedKubeconfig}"`,
        );
      }
    } catch (fileError) {
      // Arquivo não existe, usar comando original (fallback para padrão)
      console.warn(
        `Kubeconfig file not found: ${expandedKubeconfig}, using default`,
      );
    }
  }

  return command;
};

class AppUpdater {
  constructor() {
    log.transports.file.level = 'info';
    autoUpdater.logger = log;
    autoUpdater.checkForUpdatesAndNotify();
  }
}

let mainWindow: BrowserWindow | null = null;

// Armazenar sessões de terminal ativas
const terminalSessions = new Map<string, any>();

ipcMain.on('ipc-example', async (event, arg) => {
  const msgTemplate = (pingPong: string) => `IPC test: ${pingPong}`;
  console.log(msgTemplate(arg));
  event.reply('ipc-example', msgTemplate('pong'));
});

// Helper function para tratar erros de autenticação/RBAC
const handleAuthError = async (
  command: string,
  kubeconfig: string | undefined,
  originalError: any,
) => {
  const errorMessage =
    originalError instanceof Error
      ? originalError.message
      : String(originalError);

  // Verificar se é erro de autenticação ou RBAC
  if (
    errorMessage.includes('must be logged in') ||
    errorMessage.includes('provide credentials')
  ) {
    // Estratégia 1: Tentar com kubeconfig padrão se estava usando um customizado
    if (kubeconfig) {
      try {
        const defaultCommand = command; // Comando sem --kubeconfig
        const { stdout, stderr } = await execAsync(defaultCommand, {
          maxBuffer: 50 * 1024 * 1024,
        });
        return {
          success: true,
          data: stdout,
          error: null,
          fallbackUsed: 'default-kubeconfig',
        };
      } catch (fallbackError) {
        // Continua para próxima estratégia
      }
    }

    // Estratégia 2: Para comandos com field-selector complexos, tentar versão simplificada
    if (command.includes('--field-selector') && command.includes('events')) {
      try {
        // Extrair namespace do comando original
        const namespaceMatch = command.match(/-n\s+(\S+)/);
        const namespace = namespaceMatch ? namespaceMatch[1] : '';

        const simplifiedCommand = namespace
          ? `kubectl get events -n ${namespace} -o json`
          : 'kubectl get events --all-namespaces -o json';

        const finalSimplifiedCommand = await buildKubectlCommand(
          simplifiedCommand,
          kubeconfig,
        );
        const { stdout, stderr } = await execAsync(finalSimplifiedCommand, {
          maxBuffer: 50 * 1024 * 1024,
        });
        return {
          success: true,
          data: stdout,
          error: null,
          fallbackUsed: 'simplified-events',
        };
      } catch (fallbackError) {
        // Continua para próxima estratégia
      }
    }

    // Estratégia 3: Para comandos com --since-time, tentar sem ele
    if (command.includes('--since-time')) {
      try {
        const commandWithoutSince = command.replace(
          /--since-time=\S+/,
          '--tail=100',
        );
        const finalFallbackCommand = await buildKubectlCommand(
          commandWithoutSince,
          kubeconfig,
        );
        const { stdout, stderr } = await execAsync(finalFallbackCommand, {
          maxBuffer: 50 * 1024 * 1024,
        });
        return {
          success: true,
          data: stdout,
          error: null,
          fallbackUsed: 'no-since-time',
        };
      } catch (fallbackError) {
        // Continua para retorno de erro
      }
    }
  }

  // Se todas as estratégias falharam, retornar erro original
  return {
    success: false,
    data: null,
    error: errorMessage,
  };
};

// Handle kubectl commands
ipcMain.handle(
  'execute-kubectl',
  async (event, command: string, kubeconfig?: string) => {
    try {
      const finalCommand = await buildKubectlCommand(command, kubeconfig);

      const { stdout, stderr } = await execAsync(finalCommand, {
        maxBuffer: 50 * 1024 * 1024, // 50MB buffer limit
      });

      // Log apenas erros relevantes, não warnings normais
      if (stderr && !stderr.includes('No resources found')) {
        console.warn('kubectl stderr:', stderr);
      }

      return {
        success: true,
        data: stdout,
        error: null,
      };
    } catch (error) {
      // Log apenas informação essencial sobre o erro
      const errorMessage =
        error instanceof Error ? error.message : 'Unknown error';
      console.warn('kubectl command failed, trying fallback strategies...');

      // Tentar estratégias de fallback para erros de autenticação/RBAC
      const fallbackResult = await handleAuthError(command, kubeconfig, error);
      if (fallbackResult.success) {
        return fallbackResult;
      }

      // Log apenas se todas as estratégias falharam
      console.error('All kubectl strategies failed:', errorMessage);

      return {
        success: false,
        data: null,
        error: errorMessage,
      };
    }
  },
);

// Specific handler for getting node metrics (CPU and Memory usage)
ipcMain.handle(
  'get-node-metrics',
  async (event, nodeName: string, kubeconfig?: string) => {
    try {
      const command = await buildKubectlCommand(
        `kubectl top node ${nodeName} --no-headers`,
        kubeconfig,
      );
      const { stdout } = await execAsync(command);

      // Parse the output: NAME CPU(cores) CPU% MEMORY(bytes) MEMORY%
      const parts = stdout.trim().split(/\s+/);
      if (parts.length >= 5) {
        return {
          success: true,
          data: {
            cpuUsed: parts[1], // CPU cores used
            cpuPercent: parts[2], // CPU percentage
            memoryUsed: parts[3], // Memory used
            memoryPercent: parts[4], // Memory percentage
          },
          error: null,
        };
      }
      throw new Error('Invalid metrics output format');
    } catch (error) {
      console.error('get-node-metrics error:', error);
      return {
        success: false,
        data: null,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  },
);

// Specific handler for getting node pods
ipcMain.handle(
  'get-node-pods',
  async (event, nodeName: string, kubeconfig?: string) => {
    try {
      const command = await buildKubectlCommand(
        `kubectl get pods --all-namespaces --field-selector spec.nodeName=${nodeName} -o json`,
        kubeconfig,
      );
      const { stdout } = await execAsync(command);
      const podsData = JSON.parse(stdout);

      const runningPods = podsData.items.filter(
        (pod: any) =>
          pod.status.phase === 'Running' || pod.status.phase === 'Pending',
      );

      return {
        success: true,
        data: {
          total: podsData.items.length,
          running: runningPods.length,
          pods: podsData.items,
        },
        error: null,
      };
    } catch (error) {
      console.error('get-node-pods error:', error);
      return {
        success: false,
        data: null,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  },
);

// Specific handler for getting single node information
ipcMain.handle(
  'get-node-details',
  async (event, nodeName: string, kubeconfig?: string) => {
    try {
      const command = await buildKubectlCommand(
        `kubectl get node ${nodeName} -o json`,
        kubeconfig,
      );
      const { stdout } = await execAsync(command);
      const nodeData = JSON.parse(stdout);

      // Extract comprehensive node information
      const addresses = nodeData.status.addresses || [];
      const internalIP =
        addresses.find((addr: any) => addr.type === 'InternalIP')?.address ||
        '';
      const externalIP =
        addresses.find((addr: any) => addr.type === 'ExternalIP')?.address ||
        '';
      const hostname =
        addresses.find((addr: any) => addr.type === 'Hostname')?.address || '';

      // Get capacity information
      const capacity = nodeData.status.capacity || {};
      const allocatable = nodeData.status.allocatable || {};

      // Get conditions (Ready, MemoryPressure, DiskPressure, etc.)
      const conditions = nodeData.status.conditions || [];
      const readyCondition = conditions.find(
        (condition: any) => condition.type === 'Ready',
      );

      const nodeInfo = {
        // Raw data
        raw: nodeData,
        // Metadata
        metadata: {
          name: nodeData.metadata.name,
          creationTimestamp: nodeData.metadata.creationTimestamp,
          labels: nodeData.metadata.labels || {},
          annotations: nodeData.metadata.annotations || {},
        },
        // Spec
        spec: {
          unschedulable: nodeData.spec?.unschedulable || false,
          taints: nodeData.spec?.taints || [],
        },
        // Basic node info
        name: nodeData.metadata.name,
        labels: nodeData.metadata.labels || {},
        // Node Info (existing)
        ...nodeData.status.nodeInfo,
        // Addresses
        addresses: {
          internalIP,
          externalIP,
          hostname,
        },
        // Capacity and Allocatable resources
        capacity: {
          cpu: capacity.cpu || '0',
          memory: capacity.memory || '0',
          pods: capacity.pods || '0',
          'ephemeral-storage': capacity['ephemeral-storage'] || '0',
        },
        allocatable: {
          cpu: allocatable.cpu || '0',
          memory: allocatable.memory || '0',
          pods: allocatable.pods || '0',
          'ephemeral-storage': allocatable['ephemeral-storage'] || '0',
        },
        // Node status
        status: {
          ready: readyCondition?.status === 'True',
          readyMessage: readyCondition?.message || '',
          conditions,
        },
      };

      return {
        success: true,
        data: nodeInfo,
        error: null,
      };
    } catch (error) {
      console.error('get-node-details error:', error);
      return {
        success: false,
        data: null,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  },
);

// Specific handler for getting nodes information
ipcMain.handle('get-nodes-info', async (event, kubeconfig?: string) => {
  try {
    const command = await buildKubectlCommand(
      'kubectl get nodes -o json',
      kubeconfig,
    );
    const { stdout } = await execAsync(command);
    const nodesData = JSON.parse(stdout);

    // Extract comprehensive node information
    const nodeInfos = nodesData.items.map((node: any) => {
      // Get addresses (Internal IP, External IP, Hostname)
      const addresses = node.status.addresses || [];
      const internalIP =
        addresses.find((addr: any) => addr.type === 'InternalIP')?.address ||
        '';
      const externalIP =
        addresses.find((addr: any) => addr.type === 'ExternalIP')?.address ||
        '';
      const hostname =
        addresses.find((addr: any) => addr.type === 'Hostname')?.address || '';

      // Get capacity information
      const capacity = node.status.capacity || {};
      const allocatable = node.status.allocatable || {};

      // Get conditions (Ready, MemoryPressure, DiskPressure, etc.)
      const conditions = node.status.conditions || [];
      const readyCondition = conditions.find(
        (condition: any) => condition.type === 'Ready',
      );

      return {
        // Metadata
        metadata: {
          name: node.metadata.name,
          creationTimestamp: node.metadata.creationTimestamp,
          labels: node.metadata.labels || {},
        },
        // Spec
        spec: {
          unschedulable: node.spec?.unschedulable || false,
        },
        // Basic node info
        name: node.metadata.name,
        labels: node.metadata.labels || {},
        // Node Info (existing)
        ...node.status.nodeInfo,
        // Addresses
        addresses: {
          internalIP,
          externalIP,
          hostname,
        },
        // Capacity and Allocatable resources
        capacity: {
          cpu: capacity.cpu || '0',
          memory: capacity.memory || '0',
          pods: capacity.pods || '0',
          'ephemeral-storage': capacity['ephemeral-storage'] || '0',
        },
        allocatable: {
          cpu: allocatable.cpu || '0',
          memory: allocatable.memory || '0',
          pods: allocatable.pods || '0',
          'ephemeral-storage': allocatable['ephemeral-storage'] || '0',
        },
        // Node status
        status: {
          ready: readyCondition?.status === 'True',
          readyMessage: readyCondition?.message || '',
          conditions,
        },
      };
    });

    return {
      success: true,
      data: nodeInfos,
      error: null,
    };
  } catch (error) {
    console.error('get-nodes-info error:', error);
    return {
      success: false,
      data: null,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
});

// Terminal session handlers - COMMENTED OUT - script approach with compatibility issues
// ipcMain.handle('start-terminal-session', async (event, command: string) => {
//   try {
//     const sessionId = Math.random().toString(36).substring(2, 15);

//     console.log(`Starting terminal session: ${command}`);

//     // Use spawn directly with proper options for TTY
//     const terminalProcess = spawn('/usr/bin/script', ['-q', '/dev/null', command], {
//       stdio: ['pipe', 'pipe', 'pipe'],
//       env: {
//         ...process.env,
//         TERM: 'xterm-256color',
//         COLUMNS: '80',
//         LINES: '24'
//       },
//       detached: false,
//     });

//     // Store the process
//     terminalSessions.set(sessionId, terminalProcess);

//     // Handle stdout
//     terminalProcess.stdout?.on('data', (data) => {
//       if (mainWindow) {
//         mainWindow.webContents.send('terminal-data', sessionId, data.toString());
//       }
//     });

//     // Handle stderr
//     terminalProcess.stderr?.on('data', (data) => {
//       if (mainWindow) {
//         mainWindow.webContents.send('terminal-data', sessionId, data.toString());
//       }
//     });

//     // Handle process exit
//     terminalProcess.on('exit', (code) => {
//       console.log(`Process exited with code: ${code}`);
//       if (mainWindow) {
//         mainWindow.webContents.send('terminal-exit', sessionId, code || 0);
//       }
//       terminalSessions.delete(sessionId);
//     });

//     // Handle process error
//     terminalProcess.on('error', (error) => {
//       console.error(`Process error: ${error.message}`);
//       if (mainWindow) {
//         mainWindow.webContents.send('terminal-data', sessionId, `Error: ${error.message}\r\n`);
//         mainWindow.webContents.send('terminal-exit', sessionId, 1);
//       }
//       terminalSessions.delete(sessionId);
//     });

//     return {
//       success: true,
//       sessionId,
//       error: null,
//     };
//   } catch (error) {
//     console.error('start-terminal-session error:', error);
//     return {
//       success: false,
//       sessionId: null,
//       error: error instanceof Error ? error.message : 'Unknown error',
//     };
//   }
// });

// COMMAND-BY-COMMAND TERMINAL - Simple and functional
ipcMain.handle('start-terminal-session', async (event, command: string) => {
  try {
    const sessionId = Math.random().toString(36).substring(2, 15);

    console.log(`Starting command-by-command terminal session`);

    // Send welcome message with prompt
    if (mainWindow) {
      const welcomeMsg =
        'Terminal Simples - Digite comandos linha por linha\r\n$ ';
      console.log('Sending welcome message:', welcomeMsg);
      mainWindow.webContents.send('terminal-data', sessionId, welcomeMsg);
    }

    // Store current directory and session state
    const sessionState = {
      cwd: process.cwd(),
      env: {
        ...process.env,
        FORCE_COLOR: '1',
        TERM: 'xterm-256color',
      },
      buffer: '',
      active: true,
    };

    terminalSessions.set(sessionId, sessionState);

    return {
      success: true,
      sessionId,
      error: null,
    };
  } catch (error) {
    console.error('start-terminal-session error:', error);
    return {
      success: false,
      sessionId: null,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
});

// Terminal sessions storage

ipcMain.on('terminal-data', (event, sessionId: string, data: string) => {
  const sessionState = terminalSessions.get(sessionId);

  if (!sessionState || !sessionState.active) {
    console.error('No active session for:', sessionId);
    return;
  }

  console.log('Received terminal input:', JSON.stringify(data));

  // Handle special keys
  if (data === '\r' || data === '\n' || data === '\r\n') {
    // Enter pressed - execute command
    const command = sessionState.buffer.trim();
    console.log('Executing command:', command);

    if (command) {
      executeCommand(sessionId, command, sessionState);
    } else {
      // Empty command, just show prompt
      if (mainWindow) {
        mainWindow.webContents.send('terminal-data', sessionId, '\r\n$ ');
      }
    }
    sessionState.buffer = '';
  } else if (data === '\u007f' || data === '\b') {
    // Backspace
    if (sessionState.buffer.length > 0) {
      sessionState.buffer = sessionState.buffer.slice(0, -1);
      if (mainWindow) {
        mainWindow.webContents.send('terminal-data', sessionId, '\b \b');
      }
    }
  } else if (data >= ' ' || data === '\t') {
    // Regular character
    sessionState.buffer += data;
    if (mainWindow) {
      mainWindow.webContents.send('terminal-data', sessionId, data);
    }
  }
});

// Execute a single command
async function executeCommand(
  sessionId: string,
  command: string,
  sessionState: any,
) {
  if (!mainWindow) return;

  try {
    console.log('Executing:', command, 'in directory:', sessionState.cwd);

    // Handle cd command specially
    if (command.startsWith('cd ')) {
      const newDir = command.substring(3).trim();
      try {
        const resolvedDir = require('path').resolve(sessionState.cwd, newDir);
        // Check if directory exists
        await require('fs').promises.access(resolvedDir);
        sessionState.cwd = resolvedDir;
        mainWindow.webContents.send('terminal-data', sessionId, '\r\n$ ');
        return;
      } catch (error) {
        mainWindow.webContents.send(
          'terminal-data',
          sessionId,
          `\r\n\x1b[31mcd: ${newDir}: No such file or directory\x1b[0m\r\n$ `,
        );
        return;
      }
    }

    // Execute command using spawn
    const child = spawn('sh', ['-c', command], {
      cwd: sessionState.cwd,
      env: sessionState.env,
      stdio: ['pipe', 'pipe', 'pipe'],
    });

    let hasOutput = false;

    child.stdout?.on('data', (data) => {
      hasOutput = true;
      const output = data.toString();
      mainWindow.webContents.send('terminal-data', sessionId, output);
    });

    child.stderr?.on('data', (data) => {
      hasOutput = true;
      const errorOutput = data.toString();
      mainWindow.webContents.send(
        'terminal-data',
        sessionId,
        `\x1b[31m${errorOutput}\x1b[0m`,
      );
    });

    child.on('exit', (code) => {
      if (!hasOutput && code === 0) {
        // Command executed but no output
        mainWindow.webContents.send('terminal-data', sessionId, '\r\n$ ');
      } else {
        mainWindow.webContents.send('terminal-data', sessionId, '\r\n$ ');
      }
    });

    child.on('error', (error) => {
      mainWindow.webContents.send(
        'terminal-data',
        sessionId,
        `\r\n\x1b[31mErro: ${error.message}\x1b[0m\r\n$ `,
      );
    });
  } catch (error) {
    mainWindow.webContents.send(
      'terminal-data',
      sessionId,
      `\r\n\x1b[31mErro: ${error.message}\x1b[0m\r\n$ `,
    );
  }
}

// Handler para selecionar arquivo kubeconfig
ipcMain.handle('select-kubeconfig-file', async () => {
  const result = await dialog.showOpenDialog({
    properties: ['openFile'],
    filters: [
      { name: 'Kubeconfig Files', extensions: ['yaml', 'yml', 'config'] },
      { name: 'All Files', extensions: ['*'] },
    ],
    title: 'Selecionar arquivo Kubeconfig',
  });

  if (!result.canceled && result.filePaths.length > 0) {
    const filePath = result.filePaths[0];
    try {
      // Verificar se o arquivo existe e pode ser lido
      await fs.access(filePath, fs.constants.R_OK);

      // Ler o conteúdo do arquivo
      const content = await fs.readFile(filePath, 'utf-8');

      return {
        success: true,
        filePath,
        fileName: path.basename(filePath),
        content,
      };
    } catch (error) {
      return {
        success: false,
        error: 'Não foi possível ler o arquivo selecionado',
      };
    }
  }

  return {
    success: false,
    error: 'Nenhum arquivo selecionado',
  };
});

// Função para validar capacidades RBAC de um kubeconfig
const validateKubeconfigCapabilities = async (kubeconfigPath: string) => {
  const capabilities = {
    basicAccess: false,
    canListNodes: false,
    canListPods: false,
    canListEvents: false,
    canUseFieldSelectors: false,
    canUseSortBy: false,
    canGetLogs: false,
    limitations: [] as string[],
    warnings: [] as string[],
  };

  const testCommands = [
    {
      name: 'basicAccess',
      command: 'kubectl version --client=false --output=json',
      description: 'Conectividade básica com o cluster',
    },
    {
      name: 'canListNodes',
      command: 'kubectl get nodes -o json',
      description: 'Listar nodes',
    },
    {
      name: 'canListPods',
      command: 'kubectl get pods --all-namespaces -o json',
      description: 'Listar pods',
    },
    {
      name: 'canListEvents',
      command: 'kubectl get events --all-namespaces -o json',
      description: 'Listar eventos básicos',
    },
  ];

  // Testes avançados que podem falhar em clusters restritivos
  const advancedTests = [
    {
      name: 'canUseFieldSelectors',
      command: 'kubectl auth can-i get events --verb=list --all-namespaces',
      description: 'Permissões para filtros complexos',
    },
    {
      name: 'canUseSortBy',
      command: 'kubectl auth can-i get events --verb=list --all-namespaces',
      description: 'Permissões para ordenação',
    },
  ];

  // Teste básico de funcionalidade essencial
  for (const test of testCommands) {
    try {
      const command = await buildKubectlCommand(test.command, kubeconfigPath);
      await execAsync(command, {
        maxBuffer: 10 * 1024 * 1024,
        timeout: 8000, // 8 segundos timeout
      });
      capabilities[test.name as keyof typeof capabilities] = true;
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : String(error);

      if (
        errorMessage.includes('must be logged in') ||
        errorMessage.includes('provide credentials') ||
        errorMessage.includes('Unauthorized') ||
        errorMessage.includes('forbidden')
      ) {
        capabilities.limitations.push(`❌ ${test.description}: Sem permissão`);
      } else if (errorMessage.includes('timeout')) {
        capabilities.warnings.push(
          `⚠️ ${test.description}: Timeout (cluster lento)`,
        );
      } else {
        capabilities.warnings.push(
          `⚠️ ${test.description}: ${errorMessage.split('\n')[0]}`,
        );
      }
    }
  }

  // Se passou nos testes básicos, assumir que funcionalidades avançadas também funcionam
  // (Apenas alertar sobre limitações conhecidas se for o kubeconfig problemático específico)
  if (capabilities.basicAccess && capabilities.canListEvents) {
    capabilities.canUseFieldSelectors = true;
    capabilities.canUseSortBy = true;

    // Teste específico para o kubeconfig problemático que conhecemos
    if (kubeconfigPath.includes('integrada.yaml')) {
      try {
        const problematicCommand = await buildKubectlCommand(
          'kubectl get events -n cattle-fleet-local-system --field-selector involvedObject.kind=Deployment,involvedObject.name=fleet-agent -o json',
          kubeconfigPath,
        );
        await execAsync(problematicCommand, { timeout: 5000 });
      } catch (error) {
        const errorMessage =
          error instanceof Error ? error.message : String(error);
        if (
          errorMessage.includes('must be logged in') ||
          errorMessage.includes('provide credentials')
        ) {
          capabilities.canUseFieldSelectors = false;
          capabilities.limitations.push(
            `❌ Field selectors complexos: RBAC limitado para combinações específicas`,
          );
        }
      }
    }
  }

  // Teste específico para logs (usando um pod real)
  try {
    const command = await buildKubectlCommand(
      'kubectl get pods --all-namespaces --no-headers -o custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace',
      kubeconfigPath,
    );
    const { stdout } = await execAsync(command, { timeout: 5000 });

    if (stdout.trim()) {
      const lines = stdout.trim().split('\n');
      // Pegar o primeiro pod disponível
      const [podName, namespace] = lines[0].split(/\s+/);

      if (
        podName &&
        namespace &&
        podName !== '<none>' &&
        namespace !== '<none>'
      ) {
        try {
          const logsCommand = await buildKubectlCommand(
            `kubectl logs ${podName} -n ${namespace} --tail=1`,
            kubeconfigPath,
          );
          await execAsync(logsCommand, { timeout: 5000 });
          capabilities.canGetLogs = true;
        } catch (logError) {
          const errorMessage =
            logError instanceof Error ? logError.message : String(logError);
          if (
            errorMessage.includes('must be logged in') ||
            errorMessage.includes('provide credentials') ||
            errorMessage.includes('Unauthorized') ||
            errorMessage.includes('forbidden')
          ) {
            capabilities.limitations.push(`❌ Visualizar logs: Sem permissão`);
          } else {
            capabilities.warnings.push(
              `⚠️ Visualizar logs: ${errorMessage.split('\n')[0]}`,
            );
          }
        }
      } else {
        capabilities.warnings.push(
          `⚠️ Visualizar logs: Nenhum pod encontrado para teste`,
        );
      }
    } else {
      capabilities.warnings.push(
        `⚠️ Visualizar logs: Nenhum pod disponível para teste`,
      );
    }
  } catch {
    // Se não conseguiu nem listar pods, logs também não vão funcionar
    capabilities.limitations.push(
      `❌ Visualizar logs: Dependente de permissões de pods`,
    );
  }

  return capabilities;
};

// Handler para salvar conteúdo de kubeconfig em arquivo
ipcMain.handle(
  'save-kubeconfig-content',
  async (event, fileName: string, content: string) => {
    try {
      // Criar diretório .kube-now/configs se não existir
      const homeDir = require('os').homedir();
      const configDir = path.join(homeDir, '.kube-now', 'configs');

      await fs.mkdir(configDir, { recursive: true });

      // Gerar nome único para o arquivo
      const timestamp = Date.now();
      const safeFileName = fileName.replace(/[^a-zA-Z0-9-]/g, '-');
      const finalFileName = `${safeFileName}-${timestamp}.yaml`;
      const filePath = path.join(configDir, finalFileName);

      // Salvar o conteúdo
      await fs.writeFile(filePath, content, 'utf-8');

      return {
        success: true,
        filePath,
      };
    } catch (error) {
      console.error('Error saving kubeconfig:', error);
      return {
        success: false,
        error:
          error instanceof Error ? error.message : 'Erro ao salvar arquivo',
      };
    }
  },
);

// Handler para validar capacidades de um kubeconfig
ipcMain.handle(
  'validate-kubeconfig-capabilities',
  async (event, kubeconfigPath: string) => {
    try {
      const capabilities = await validateKubeconfigCapabilities(kubeconfigPath);

      return {
        success: true,
        capabilities,
      };
    } catch (error) {
      return {
        success: false,
        error:
          error instanceof Error ? error.message : 'Erro ao validar kubeconfig',
        capabilities: {
          basicAccess: false,
          canListNodes: false,
          canListPods: false,
          canListEvents: false,
          canUseFieldSelectors: false,
          canUseSortBy: false,
          canGetLogs: false,
          limitations: ['❌ Erro durante validação'],
          warnings: [],
        },
      };
    }
  },
);

ipcMain.handle('kill-terminal-session', async (event, sessionId: string) => {
  const sessionState = terminalSessions.get(sessionId);
  if (sessionState) {
    try {
      sessionState.active = false;
      terminalSessions.delete(sessionId);
      return { success: true };
    } catch (error) {
      console.error('Error killing terminal session:', error);
      return { success: false, error: error.message };
    }
  }
  return { success: false, error: 'Session not found' };
});

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support');
  sourceMapSupport.install();
}

const isDebug =
  process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';

if (isDebug) {
  require('electron-debug').default();
}

const installExtensions = async () => {
  const installer = require('electron-devtools-installer');
  const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
  const extensions = ['REACT_DEVELOPER_TOOLS'];

  return installer
    .default(
      extensions.map((name) => installer[name]),
      forceDownload,
    )
    .catch(console.log);
};

const createWindow = async () => {
  if (isDebug) {
    await installExtensions();
  }

  const RESOURCES_PATH = app.isPackaged
    ? path.join(process.resourcesPath, 'assets')
    : path.join(__dirname, '../../assets');

  const getAssetPath = (...paths: string[]): string => {
    return path.join(RESOURCES_PATH, ...paths);
  };

  mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    icon: getAssetPath('icon.png'),
    webPreferences: {
      preload: app.isPackaged
        ? path.join(__dirname, 'preload.js')
        : path.join(__dirname, '../../.erb/dll/preload.js'),
      devTools: true,
    },
  });

  mainWindow.loadURL(resolveHtmlPath('index.html'));

  mainWindow.on('ready-to-show', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize();
    } else {
      mainWindow.show();
    }

    // Open DevTools automatically in development
    if (isDebug) {
      mainWindow.webContents.openDevTools();

      // Monitor and suppress common Electron development warnings
      mainWindow.webContents.on('console-message', (event, level, message) => {
        // Log security-relevant errors but suppress graphics/UI warnings
        if (
          message.includes('Autofill') ||
          message.includes('SharedImageManager') ||
          message.includes('sandboxed_renderer') ||
          message.includes('mailbox')
        ) {
          // These are harmless graphics/UI warnings in development
          return;
        }

        // Log potentially important messages
        if (level >= 2) {
          // Warnings and errors
          console.log(`Renderer: [${level}] ${message}`);
        }
      });
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();

  // Open urls in the user's browser
  mainWindow.webContents.setWindowOpenHandler((edata) => {
    shell.openExternal(edata.url);
    return { action: 'deny' };
  });

  // Remove this if your app does not use auto updates
  // eslint-disable-next-line
  new AppUpdater();
};

/**
 * Add event listeners...
 */

app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app
  .whenReady()
  .then(() => {
    createWindow();
    app.on('activate', () => {
      // On macOS it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (mainWindow === null) createWindow();
    });
  })
  .catch(console.log);
