package com.aegis.camera.service.impl;

import com.aegis.camera.config.ZLMediaKitProperties;
import com.aegis.camera.domain.Camera;
import com.aegis.camera.service.ZLMediaKitService;
import com.aegis.camera.service.StreamProtocolHandler;
import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * ZLMediaKit 集成实现
 *
 * 说明：
 * - 当前实现主要面向 RTSP 拉流场景，通过 /index/api/addStreamProxy / close_stream 等接口控制流；
 * - GB28181/RTMP/ONVIF 等协议可在后续根据需要扩展；
 * - 解析 Camera.extraConfig 时约定为 JSON 字符串，至少包含 "url" 字段（RTSP 地址）。
 */
@Slf4j
@Service
public class ZLMediaKitServiceImpl implements ZLMediaKitService {

    private static final String DEFAULT_SCHEMA_HTTP = "http";

    @Autowired
    private ZLMediaKitProperties properties;

    @Autowired
    private List<StreamProtocolHandler> protocolHandlers;

    @Override
    public boolean startStream(Camera camera) {
        if (camera == null) {
            throw new ServiceException("摄像头信息不能为空");
        }
        String protocol = camera.getProtocol();
        if (StringUtils.isBlank(protocol)) {
            throw new ServiceException("摄像头协议类型不能为空");
        }
        StreamProtocolHandler handler = getHandler(protocol);
        return handler.startStream(camera, properties);
    }

    @Override
    public boolean stopStream(Camera camera) {
        if (camera == null) {
            throw new ServiceException("摄像头信息不能为空");
        }
        String protocol = camera.getProtocol();
        if (StringUtils.isBlank(protocol)) {
            throw new ServiceException("摄像头协议类型不能为空");
        }
        StreamProtocolHandler handler = getHandler(protocol);
        return handler.stopStream(camera, properties);
    }

    @Override
    public Map<String, String> getPlayUrls(String cameraCode) {
        if (StringUtils.isBlank(cameraCode)) {
            return Collections.emptyMap();
        }
        // 返回相对路径，由前端根据自身协议/域名/端口构建完整 URL，避免在后端硬编码外网地址
        Map<String, String> urls = new HashMap<>();
        // HLS 相对路径，例如：/live/{cameraCode}/hls.m3u8
        urls.put("hls", String.format("/%s/%s/%s.m3u8",
            properties.getApp(), cameraCode, "hls"));
        // HTTP-FLV 相对路径，例如：/live/{cameraCode}.live.flv
        urls.put("flv", String.format("/%s/%s.live.flv",
            properties.getApp(), cameraCode));
        // WebSocket-FLV 相对路径（前端需根据协议选择 ws/wss）
        urls.put("wsFlv", String.format("/%s/%s.live.flv",
            properties.getApp(), cameraCode));
        return urls;
    }

    private StreamProtocolHandler getHandler(String protocol) {
        if (protocolHandlers == null || protocolHandlers.isEmpty()) {
            throw new ServiceException("未找到任何摄像头协议处理器，请检查 Spring 配置");
        }
        return protocolHandlers.stream()
            .filter(h -> protocol.equalsIgnoreCase(h.getProtocol()))
            .findFirst()
            .orElseThrow(() -> new ServiceException("不支持的协议类型: " + protocol));
    }
}