package weblive

import (
	"encoding/json"
	"os"
	"strings"

	"github.com/pion/webrtc/v3"
)

// MediaEngine 与 API 构建（全局复用，避免重复注册编解码器）
// 部署在 Docker/NAT 后若观众端黑屏、信令正常，请设置 LIVE_PUBLIC_IP 为本机公网 IPv4（与域名解析一致，可逗号分隔多个）。
func buildAPI() (*webrtc.API, error) {
	m := &webrtc.MediaEngine{}
	if err := m.RegisterDefaultCodecs(); err != nil {
		return nil, err
	}
	se := webrtc.SettingEngine{}
	if raw := strings.TrimSpace(os.Getenv("LIVE_PUBLIC_IP")); raw != "" {
		parts := strings.Split(raw, ",")
		var ips []string
		for _, p := range parts {
			p = strings.TrimSpace(p)
			if p != "" {
				ips = append(ips, p)
			}
		}
		if len(ips) > 0 {
			se.SetNAT1To1IPs(ips, webrtc.ICECandidateTypeHost)
		}
	}
	api := webrtc.NewAPI(
		webrtc.WithMediaEngine(m),
		webrtc.WithSettingEngine(se),
	)
	return api, nil
}

func iceServersFromEnv() []webrtc.ICEServer {
	raw := strings.TrimSpace(os.Getenv("LIVE_ICE_SERVERS"))
	if raw == "" {
		return []webrtc.ICEServer{
			{URLs: []string{"stun:stun.l.google.com:19302"}},
		}
	}
	var servers []webrtc.ICEServer
	if err := json.Unmarshal([]byte(raw), &servers); err != nil {
		return []webrtc.ICEServer{{URLs: []string{"stun:stun.l.google.com:19302"}}}
	}
	return servers
}
