package com.agentui.desktop

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import org.json.JSONObject
import java.io.File

class MainActivity : TauriActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        syncServerUrlToPrefs()
    }

    override fun onResume() {
        super.onResume()
        syncServerUrlToPrefs()
    }

    /**
     * Reads the Tauri plugin-store settings.json and syncs serverUrl
     * to SharedPreferences so native components (widget, voice) can use it.
     */
    private fun syncServerUrlToPrefs() {
        try {
            val storeFile = File(filesDir, "app_tauri-plugin-store/settings.json")
            if (!storeFile.exists()) return

            val json = JSONObject(storeFile.readText())
            val serverUrl = json.optString("serverUrl", "")
            if (serverUrl.isNotEmpty()) {
                ServerConfig.setServerUrl(this, serverUrl)
                Log.d("AgentUI", "Synced serverUrl to prefs: $serverUrl")
            }
        } catch (e: Exception) {
            Log.w("AgentUI", "Failed to sync server URL", e)
        }
    }
}
