package com.agentui.desktop

import android.content.Context

object ServerConfig {
    private const val PREFS_NAME = "agent_ui_config"
    private const val KEY_SERVER_URL = "server_url"

    fun getServerUrl(context: Context): String? {
        return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(KEY_SERVER_URL, null)
    }

    fun setServerUrl(context: Context, url: String) {
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .edit()
            .putString(KEY_SERVER_URL, url.trimEnd('/'))
            .apply()
    }

    /** e.g. "http://192.168.1.10:4103" */
    fun terminalBaseUrl(context: Context): String? {
        val base = getServerUrl(context) ?: return null
        val uri = android.net.Uri.parse(base)
        val host = uri.host ?: return null
        return "${uri.scheme}://$host:4103"
    }

    /** e.g. "ws://192.168.1.10:4103" */
    fun terminalWsUrl(context: Context): String? {
        val base = terminalBaseUrl(context) ?: return null
        return base.replace("http://", "ws://").replace("https://", "wss://")
    }

    /** e.g. "http://192.168.1.10:4100/api" */
    fun apiBaseUrl(context: Context): String? {
        val base = getServerUrl(context) ?: return null
        return "${base.trimEnd('/')}/api"
    }
}
