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

import com.usky.cdi.service.sip.config.SipServerProperties;
import com.usky.cdi.service.sip.listener.SipServerListener;
import com.usky.cdi.service.sip.model.VideoStreamSession;
import com.usky.cdi.service.sip.service.VideoStreamManager;
import com.usky.cdi.service.sip.util.PortAllocator;

/**
 * 本地 SIP 收发集成测试：启动服务端并模拟设备推流。
 */
public class SipLocalIntegrationTestMain {

    public static void main(String[] args) throws Exception {
        int sipPort = 15060;
        SipServerProperties properties = new SipServerProperties();
        properties.setEnabled(true);
        properties.setHost("127.0.0.1");
        properties.setPort(sipPort);
        properties.setLocalIp("127.0.0.1");
        properties.setRtpPortMin(30100);
        properties.setRtpPortMax(30200);

        PortAllocator portAllocator = new PortAllocator(properties);
        VideoStreamManager streamManager = new VideoStreamManager(properties, portAllocator);
        SipServerListener listener = new SipServerListener(properties, streamManager);

        listener.start();
        Thread.sleep(500);
        System.out.println("SIP 服务端已启动: 127.0.0.1:" + sipPort);

        SipVideoPusher pusher = new SipVideoPusher(
                "127.0.0.1", sipPort,
                "34020000001320000001",
                properties.getPlatformId(),
                3,
                "127.0.0.1"
        );
        SipVideoPusher.PushResult result = pusher.push();

        Thread.sleep(500);
        VideoStreamSession session = result.getCallId() != null
                ? streamManager.getSession(result.getCallId()) : null;

        System.out.println("--- 测试结果 ---");
        System.out.println("pushSuccess=" + result.isSuccess());
        System.out.println("packetsSent=" + result.getPacketsSent());
        if (session != null) {
            System.out.println("receivedPackets=" + session.getReceivedPackets().get());
            System.out.println("receivedBytes=" + session.getReceivedBytes().get());
            System.out.println("localRtpPort=" + session.getLocalRtpPort());
        } else {
            System.out.println("serverSession=null");
        }
        if (!result.getErrors().isEmpty()) {
            System.out.println("errors=" + result.getErrors());
        }

        listener.stop();
        boolean ok = result.isSuccess()
                && session != null
                && session.getReceivedPackets().get() > 0;
        System.out.println(ok ? "PASS" : "FAIL");
        System.exit(ok ? 0 : 1);
    }
}
