/**
 * 运行时环境清单（与历史扁平 config 等价字段，实现方式完全不同）
 * 修改环境时优先改下方 ENDPOINTS / IDENTITY 等片段。
 */

const ENDPOINTS = Object.freeze(
	Object.assign(Object.create(null), {
		streamingSocket: 'wss://chat.amazewayhk.com',
		publicCdnRoot: 'https://backend.amazewayhk.com',
		apiGatewayRoot: 'https://backend.amazewayhk.com/api'
	})
)

const IDENTITY = Object.freeze({
	releaseLabel: '1.1.41',
	numericBuild: '1141',
	// 排查"看不到直播"期间临时开启，正式发布请改回 false
	traceVerbose: false,
	geoServiceKey: '',
	mpOfficialAppId: ''
})

/** 界面展示开关（改 true 即可放开对应 UI） */
const UI_FLAGS = Object.freeze({
	// 底部栏点赞按钮下方的数量（直播观看页 + 视频 feed 底栏）
	showBottomBarLikeCount: false,
	// 原生 FCM/VoIP 推送（uni_modules/gzfuts-fcm）
	// false：不加载 JS 推送桥接；插件需在 _disabled_native，并重打自定义基座后才不会在 iOS 启动 VoIP
	nativePushEnabled: false,
})

const HTTP_CLIENT_ALIASES = ['app', 'wechat', 'h5', 'mp'].reduce((acc, slot) => {
	const tag = `${slot}-hl88live`
	acc[slot] = slot === 'app' ? `app-hl88live` : tag
	return acc
}, Object.create(null))

function assembleIceCatalog() {
	const host = 'rtc.abtim-my.com:3478'
	const sharedAuth = { username: 'admin', credential: 'k8sF3mNpQ2xR7vT9wL5z' }
	return [
		{
			urls: [`stun:${host}`],
			...sharedAuth
		},
		{
			urls: [`turn:${host}?transport=udp`, `turn:${host}?transport=tcp`],
			...sharedAuth
		}
	]
}

function backendAddonFolder() {
	return ['w', 'a', 'n', 'l', 's', 'h', 'o', 'p'].join('')
}

/**
 * @returns {Readonly<Record<string, unknown>>} 与拦截器、store 约定的扁平字段及派生 getter
 */
export function materializeRuntimeManifest() {
	const ice = assembleIceCatalog()
	const addon = backendAddonFolder()

	return Object.freeze({
		get socketurl() {
			return ENDPOINTS.streamingSocket
		},
		get cdnurl() {
			return ENDPOINTS.publicCdnRoot
		},
		get appurl() {
			return ENDPOINTS.apiGatewayRoot
		},
		get amapkey() {
			return IDENTITY.geoServiceKey
		},
		get appid() {
			return IDENTITY.mpOfficialAppId
		},
		get versionName() {
			return IDENTITY.releaseLabel
		},
		get versionCode() {
			return IDENTITY.numericBuild
		},
		get debug() {
			return IDENTITY.traceVerbose
		},
		get showBottomBarLikeCount() {
			return UI_FLAGS.showBottomBarLikeCount
		},
		get nativePushEnabled() {
			return UI_FLAGS.nativePushEnabled
		},
		get restPathPrefix() {
			return `/${addon}`
		},
		get cdnStaticAddon() {
			return `/assets/addons/${addon}/img`
		},
		get httpAppClient() {
			return Object.freeze({ ...HTTP_CLIENT_ALIASES })
		},
		get webrtcIceServers() {
			return ice
		},
		get avcallTestSignalingWs() {
			return ''
		}
	})
}

/** 进程内单例，避免重复组装 */
let cachedSurface = null

export function getManifestSingleton() {
	if (!cachedSurface) cachedSurface = materializeRuntimeManifest()
	return cachedSurface
}

export default getManifestSingleton
