/**
 * CLIProxy Lifecycle Management
 *
 * Handles:
 * - ccs cliproxy start
 * - ccs cliproxy restart
 * - ccs cliproxy status
 * - ccs cliproxy stop
 */

import { initUI, header, color, dim, ok, warn, info } from '../../utils/ui';
import { getProxyStatus, startProxy, stopProxy } from '../../cliproxy/services';
import { detectRunningProxy } from '../../cliproxy/proxy-detector';
import { resolveLifecyclePort } from './resolve-lifecycle-port';

export async function handleStart(verbose = false): Promise<void> {
  await initUI();
  console.log(header('Start CLIProxy'));
  console.log('');

  const port = resolveLifecyclePort();
  const result = await startProxy(port, verbose);
  if (result.started) {
    if (result.alreadyRunning) {
      console.log(info(`CLIProxy already running on port ${result.port}`));
      if (result.configRegenerated) {
        console.log(warn('Config updated - restart CLIProxy to apply changes'));
      }
    } else {
      console.log(ok(`CLIProxy started on port ${result.port}`));
    }
    console.log(dim('To stop: ccs cliproxy stop'));
  } else {
    console.log(warn(result.error || 'Failed to start CLIProxy'));
  }
  console.log('');
}

export async function handleRestart(verbose = false): Promise<void> {
  await initUI();
  console.log(header('Restart CLIProxy'));
  console.log('');

  const port = resolveLifecyclePort();
  const stopResult = await stopProxy(port);
  if (stopResult.stopped) {
    console.log(ok(`CLIProxy stopped (PID ${stopResult.pid})`));
  } else if (stopResult.error === 'No active CLIProxy session found') {
    console.log(info('No active CLIProxy session found, starting a new instance'));
  } else {
    console.log(warn(stopResult.error || 'Failed to stop existing CLIProxy'));
    console.log(info('Attempting to start a fresh instance...'));
  }

  const startResult = await startProxy(port, verbose);
  if (startResult.started) {
    if (startResult.alreadyRunning) {
      console.log(info(`CLIProxy already running on port ${startResult.port}`));
    } else {
      console.log(ok(`CLIProxy started on port ${startResult.port}`));
    }
  } else {
    console.log(warn(startResult.error || 'Failed to restart CLIProxy'));
  }

  console.log('');
}

export async function handleProxyStatus(): Promise<void> {
  await initUI();
  console.log(header('CLIProxy Status'));
  console.log('');

  const port = resolveLifecyclePort();
  const status = getProxyStatus(port);
  if (status.running) {
    console.log(`  Status:     ${color('Running', 'success')}`);
    console.log(`  PID:        ${status.pid}`);
    console.log(`  Port:       ${status.port}`);
    console.log(`  Sessions:   ${status.sessionCount || 0} active`);
    if (status.startedAt) {
      console.log(`  Started:    ${new Date(status.startedAt).toLocaleString()}`);
    }
    console.log('');
    console.log(dim('To stop: ccs cliproxy stop'));
  } else {
    // Fallback: detect untracked/orphaned proxy process (e.g. detached session without lock file).
    const detected = await detectRunningProxy(port);
    if (detected.running && detected.verified) {
      console.log(`  Status:     ${color('Running', 'success')}`);
      console.log(`  PID:        ${detected.pid ?? 'unknown'}`);
      console.log(`  Port:       ${port}`);
      console.log(`  Sessions:   ${detected.sessionCount || 0} active`);
      if (!detected.sessionCount) {
        console.log(dim('  Note: Detected running proxy without local session lock'));
      }
      console.log('');
      console.log(dim('To stop: ccs cliproxy stop'));
    } else {
      console.log(`  Status:     ${color('Not running', 'warning')}`);
      console.log('');
      console.log(dim('CLIProxy starts automatically when you run ccs gemini, codex, etc.'));
    }
  }
  console.log('');
}

export async function handleStop(): Promise<void> {
  await initUI();
  console.log(header('Stop CLIProxy'));
  console.log('');

  const port = resolveLifecyclePort();
  const result = await stopProxy(port);
  if (result.stopped) {
    console.log(ok(`CLIProxy stopped (PID ${result.pid})`));
    if (result.sessionCount && result.sessionCount > 0) {
      console.log(info(`${result.sessionCount} active session(s) were disconnected`));
    }
  } else {
    console.log(warn(result.error || 'Failed to stop CLIProxy'));
  }
  console.log('');
}
