package com.usky.cdi.service.sip.push;

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 org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.StandardEnvironment;

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

/**
 * 命令行 RTSP 推流测试入口（独立运行，不参与 Spring Boot 组件扫描）。
 */
public class SipVideoPushTestMain {

    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("用法: SipVideoPushTestMain <deviceId> <rtspUrl> [durationSeconds]");
            System.exit(2);
        }
        String deviceId = args[0];
        String rtspUrl = args[1];
        int duration = args.length > 2 ? Integer.parseInt(args[2]) : 60;

        SipClientProperties props = loadProperties();
        Gb28181DeviceSimulator simulator = new Gb28181DeviceSimulator(props);
        simulator.register(deviceId);
        sleepUntilRegistered(simulator, 10);

        try {
            SipVideoPusherFactory factory = new SipVideoPusherFactory(simulator, props);
            Gb28181StreamResult result = factory.pushRtsp(rtspUrl, duration);
            System.out.println("success=" + result.isSuccess());
            System.out.println("packetsSent=" + result.getPacketsSent());
            if (!result.getErrors().isEmpty()) {
                System.out.println("errors=" + result.getErrors());
            }
            System.exit(result.isSuccess() ? 0 : 1);
        } finally {
            simulator.destroy();
        }
    }

    private static SipClientProperties loadProperties() {
        Map<String, Object> map = new HashMap<>();
        map.put("sip.client.enabled", "true");
        map.put("sip.client.auto-start", "false");
        map.put("sip.client.server-host", env("SIP_SERVER_HOST", "114.80.201.142"));
        map.put("sip.client.server-port", env("SIP_SERVER_PORT", "15060"));
        map.put("sip.client.domain", env("SIP_DOMAIN", "3402000000"));
        map.put("sip.client.platform-id", env("SIP_PLATFORM_ID", "34020000002000000001"));
        map.put("sip.client.password", env("SIP_PASSWORD", "jkjj_wlgz"));
        map.put("sip.client.sip-transport", env("SIP_TRANSPORT", "tcp"));
        StandardEnvironment environment = new StandardEnvironment();
        environment.getPropertySources().addFirst(new MapPropertySource("test", map));
        return Binder.get(environment)
                .bind("sip.client", SipClientProperties.class)
                .orElse(new SipClientProperties());
    }

    private static String env(String key, String def) {
        String v = System.getenv(key);
        return v != null && !v.isEmpty() ? v : def;
    }

    private static void sleepUntilRegistered(Gb28181DeviceSimulator simulator, int maxSeconds) {
        for (int i = 0; i < maxSeconds * 10; i++) {
            if (Boolean.TRUE.equals(simulator.status().get("registered"))) {
                return;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
        System.err.println("警告: 设备在 " + maxSeconds + "s 内未完成注册");
    }
}
