package com.qqchen.deploy.backend.framework.ssh;

import com.qqchen.deploy.backend.framework.enums.OsTypeEnum;
import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.framework.exception.BusinessException;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SSH命令服务工厂（Framework层）
 * 通过反射自动注册所有SSH命令服务实现
 */
@Slf4j
@Component
public class SSHCommandServiceFactory {
    
    @Autowired(required = false)
    private List<ISSHCommandService> sshCommandServices;
    
    private final Map<OsTypeEnum, ISSHCommandService> serviceMap = new HashMap<>();
    
    @PostConstruct
    public void init() {
        if (sshCommandServices == null || sshCommandServices.isEmpty()) {
            log.warn("未发现任何SSH命令服务实现");
            return;
        }
        
        for (ISSHCommandService service : sshCommandServices) {
            OsTypeEnum osType = service.getSupportedOsType();
            serviceMap.put(osType, service);
            log.info("注册SSH命令服务: {} -> {}", osType, service.getClass().getSimpleName());
        }
        
        log.info("SSH命令服务工厂初始化完成，共注册{}个服务", serviceMap.size());
    }
    
    /**
     * 根据操作系统类型获取对应的SSH命令服务
     * 
     * @param osType 操作系统类型
     * @return SSH命令服务实现
     * @throws BusinessException 不支持的OS类型时抛出
     */
    public ISSHCommandService getService(OsTypeEnum osType) {
        ISSHCommandService service = serviceMap.get(osType);
        if (service == null) {
            throw new BusinessException(ResponseCode.INVALID_PARAM,
                new Object[]{"不支持的操作系统类型: " + osType});
        }
        return service;
    }
    
    /**
     * 判断是否支持某个操作系统
     * 
     * @param osType 操作系统类型
     * @return 是否支持
     */
    public boolean isSupported(OsTypeEnum osType) {
        return serviceMap.containsKey(osType);
    }
    
    /**
     * 获取所有支持的操作系统类型
     * 
     * @return 支持的OS类型集合
     */
    public java.util.Set<OsTypeEnum> getSupportedOsTypes() {
        return serviceMap.keySet();
    }
}
