const { exec } = require('child_process');
const { promisify } = require('util');
const { getPlatformInfo } = require('../shared/platform-utils');

const execAsync = promisify(exec);

/**
 * BrowserLauncher - Opens URLs in the default browser
 */
class BrowserLauncher {
  /**
   * Open URL in default browser
   * @param {string} url - URL to open
   */
  async openURL(url) {
    try {
      const platform = getPlatformInfo();
      let command;

      switch (platform.os) {
        case 'windows':
          command = `start ${url}`;
          break;
        case 'macos':
          command = `open ${url}`;
          break;
        case 'linux':
          command = `xdg-open ${url}`;
          break;
        default:
          throw new Error(`Unsupported platform: ${platform.os}`);
      }

      await execAsync(command);

      return {
        success: true,
        url,
        platform: platform.os
      };
    } catch (error) {
      return {
        success: false,
        error: error.message,
        url
      };
    }
  }

  /**
   * Open dashboard in browser
   * @param {number} port - Port dashboard is running on
   * @param {string} hostname - Hostname (default: localhost)
   */
  async openDashboard(port = 8080, hostname = 'localhost') {
    const url = `http://${hostname}:${port}`;
    return this.openURL(url);
  }

  /**
   * Wait for service to be ready before opening
   * @param {string} url - URL to check
   * @param {number} maxAttempts - Maximum number of attempts
   * @param {number} delayMs - Delay between attempts in milliseconds
   */
  async waitForService(url, maxAttempts = 30, delayMs = 1000) {
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        const response = await fetch(url);
        if (response.ok) {
          return { success: true, attempts: attempt };
        }
      } catch (error) {
        // Service not ready yet, continue waiting
      }

      if (attempt < maxAttempts) {
        await new Promise(resolve => setTimeout(resolve, delayMs));
      }
    }

    return {
      success: false,
      error: `Service did not become ready after ${maxAttempts} attempts`
    };
  }

  /**
   * Open dashboard after waiting for it to be ready
   * @param {number} port - Port dashboard is running on
   * @param {string} hostname - Hostname (default: localhost)
   */
  async openDashboardWhenReady(port = 8080, hostname = 'localhost') {
    const url = `http://${hostname}:${port}`;

    // Wait for service to be ready
    const waitResult = await this.waitForService(url);

    if (!waitResult.success) {
      return {
        success: false,
        error: waitResult.error
      };
    }

    // Open in browser
    return this.openURL(url);
  }
}

module.exports = BrowserLauncher;
