/**
 * 云服务器控制四层架构API控制器
 * 根据文档 ARCHIVE/01_Architecture/12_Operation_Agent.md 规范实现
 */

import { Context } from 'koa';
import { CloudControlLayerService, ControlCommand, ControlResult, LayerStatus } from '../services/cloud-control-layer';

/**
 * 执行控制命令
 */
export async function executeCommand(ctx: Context) {
  try {
    const command: ControlCommand = ctx.request.body;
    
    // 验证命令格式
    if (!command || !command.type || !command.target || !command.action) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        error: 'Invalid command format',
      };
      return;
    }

    const service = CloudControlLayerService.getInstance();
    const result = await service.executeCommand(command);

    ctx.status = 200;
    ctx.body = result;
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      error: error.message,
    };
  }
}

/**
 * 获取所有层级状态
 */
export async function getLayerStatus(ctx: Context) {
  try {
    const service = CloudControlLayerService.getInstance();
    const statuses = await service.getLayerStatus();

    ctx.status = 200;
    ctx.body = statuses;
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      error: error.message,
    };
  }
}

/**
 * 测试层级连接
 */
export async function testLayer(ctx: Context) {
  try {
    const { layer } = ctx.params;
    const service = CloudControlLayerService.getInstance();
    const success = await service.testLayer(layer);

    ctx.status = 200;
    ctx.body = {
      success,
      layer,
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      error: error.message,
    };
  }
}

/**
 * 获取层级统计信息
 */
export async function getLayerStats(ctx: Context) {
  try {
    const service = CloudControlLayerService.getInstance();
    const stats = service.getLayerStats();

    ctx.status = 200;
    ctx.body = stats;
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      error: error.message,
    };
  }
}

/**
 * 健康检查
 */
export async function healthCheck(ctx: Context) {
  try {
    const service = CloudControlLayerService.getInstance();
    const statuses = await service.getLayerStatus();
    const availableLayers = statuses.filter(s => s.available);

    ctx.status = 200;
    ctx.body = {
      status: 'healthy',
      availableLayers: availableLayers.length,
      totalLayers: statuses.length,
      timestamp: Date.now(),
    };
  } catch (error) {
    ctx.status = 503;
    ctx.body = {
      status: 'unhealthy',
      error: error.message,
      timestamp: Date.now(),
    };
  }
}