package com.kingdee.eas.custom.integration.base.service.detection;

import com.kingdee.eas.custom.integration.base.bizEnum.DeviceType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 平台检测聚合服务。
 *
 * <p>通过 Spring 自动收集所有 {@link PlatformDetector} 实现，
 * 遍历匹配 User-Agent，返回平台+终端检测结果。</p>
 *
 * <p>新增平台：实现 PlatformDetector 并注册为 Spring Bean 即可，
 * 无需修改本类和 Controller。</p>
 */
@Service
public class PlatformDetectionService {

    private static final Logger log = LoggerFactory.getLogger(PlatformDetectionService.class);

    private final List<PlatformDetector> detectors;
    private final Map<String, PlatformDetector> detectorMap;

    public PlatformDetectionService(List<PlatformDetector> detectors) {
        this.detectors = detectors;
        this.detectorMap = detectors.stream().collect(Collectors.toMap(
                PlatformDetector::platform, Function.identity()));
        log.info("registered {} platform detectors: {}",
                detectors.size(),
                detectors.stream().map(PlatformDetector::platform)
                        .sorted().collect(Collectors.joining(", ")));
    }

    /**
     * 检测平台+终端复合标识。
     *
     * @param userAgent HTTP User-Agent 头
     * @return 复合标识（如 "dingtalk_mobile"、"feishu_desktop"），无法识别时返回 null
     */
    public String detect(String userAgent) {
        if (userAgent == null || userAgent.trim().isEmpty()) return null;

        for (PlatformDetector detector : detectors) {
            String result = detector.detect(userAgent);
            if (result != null) {
                log.debug("detected platform={}", result);
                return result;
            }
        }

        log.warn("unsupported client, UA={}", userAgent);
        return null;
    }

    /**
     * 检测基础平台标识，用于配置查找。
     *
     * @param userAgent HTTP User-Agent 头
     * @return 平台标识（如 "dingtalk"、"feishu"），与 oauth-config.json 中 platform 字段一致
     */
    public String detectBasePlatform(String userAgent) {
        if (userAgent == null || userAgent.trim().isEmpty()) return null;

        for (PlatformDetector detector : detectors) {
            String result = detector.detect(userAgent);
            if (result != null) {
                return detector.platform();
            }
        }

        log.warn("unsupported client, UA={}", userAgent);
        return null;
    }

    /**
     * 检测终端类型。
     *
     * @param userAgent HTTP User-Agent 头
     * @return {@link DeviceType#MOBILE} 或 {@link DeviceType#DESKTOP}，无法识别时返回 null
     */
    public DeviceType detectDevice(String userAgent) {
        if (userAgent == null || userAgent.trim().isEmpty()) return null;

        for (PlatformDetector detector : detectors) {
            DeviceType result = detector.detectDevice(userAgent);
            if (result != null) {
                return result;
            }
        }
        return null;
    }
}
