package com.usky.cdi.service.impl;

import com.usky.cdi.service.sip.config.SipClientProperties;
import com.usky.cdi.service.sip.device.Gb28181DeviceSimulator;
import com.usky.cdi.service.sip.device.Gb28181StreamResult;
import com.usky.common.core.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * GB28181 SIP 模拟摄像机推流：手动 REGISTER + RTSP → PS/RTP。
 */
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "sip.client", name = "enabled", havingValue = "true")
public class SipRtspPushService {

    private final SipClientProperties properties;
    private final Gb28181DeviceSimulator deviceSimulator;

    public Map<String, Object> pushRtspStream(String rtspUrl, Integer durationSeconds) {
        if (!StringUtils.hasText(rtspUrl)) {
            throw new BusinessException("rtspUrl 不能为空");
        }
        int duration = durationSeconds != null ? durationSeconds : properties.getDefaultDurationSeconds();
        Gb28181StreamResult result = deviceSimulator.bindRtspAndWait(
                rtspUrl, properties.getInviteWaitSeconds(), duration);
        return toMap(result);
    }

    public Map<String, Object> registerDevice(String deviceId) {
        return registerDevice(deviceId, null);
    }

    public Map<String, Object> registerDevice(String deviceId, String channelId) {
        try {
            Map<String, Object> status = deviceSimulator.register(deviceId, channelId);
            if (!Boolean.TRUE.equals(status.get("registered"))) {
                Object err = status.get("lastRegisterError");
                throw new BusinessException(err != null ? err.toString() : "GB28181 注册失败，请检查密码与平台设备配置");
            }
            return status;
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw new BusinessException(e.getMessage());
        }
    }

    public Map<String, Object> unregisterDevice() {
        return deviceSimulator.unregister();
    }

    public Map<String, Object> deviceStatus() {
        return deviceSimulator.status();
    }

    private Map<String, Object> toMap(Gb28181StreamResult result) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", result.isSuccess());
        map.put("rtspUrl", result.getRtspUrl());
        map.put("deviceId", deviceSimulator.status().get("deviceId"));
        map.put("serverHost", properties.getServerHost());
        map.put("serverPort", properties.getServerPort());
        map.put("callId", result.getCallId());
        map.put("localRtpPort", result.getLocalRtpPort());
        map.put("remoteRtpHost", result.getRemoteRtpHost());
        map.put("remoteRtpPort", result.getRemoteRtpPort());
        map.put("packetsSent", result.getPacketsSent());
        map.put("errors", result.getErrors());
        return map;
    }
}
