package xyz.kusoft.tradebotmonitor

import android.content.Context

class AppPrefs(context: Context) {
    private val prefs = context.getSharedPreferences("tradebot_monitor", Context.MODE_PRIVATE)

    init {
        val saved = prefs.getString("api_base_url", null)?.trim()
        if (saved.isNullOrBlank() || saved == LEGACY_PI_API_BASE_URL) {
            prefs.edit().putString("api_base_url", DEFAULT_API_BASE_URL).apply()
        }
    }

    var apiBaseUrl: String
        get() = normalizeBaseUrl(prefs.getString("api_base_url", DEFAULT_API_BASE_URL) ?: DEFAULT_API_BASE_URL)
        set(value) = prefs.edit().putString("api_base_url", normalizeBaseUrl(value)).apply()

    var commandToken: String
        get() = prefs.getString("command_token", "") ?: ""
        set(value) = prefs.edit().putString("command_token", value.trim()).apply()

    var retrainWebhookUrl: String
        get() = prefs.getString("retrain_webhook_url", "") ?: ""
        set(value) = prefs.edit().putString("retrain_webhook_url", value.trim()).apply()

    var selectedSymbol: String
        get() = prefs.getString("selected_symbol", "BTCUSDT") ?: "BTCUSDT"
        set(value) = prefs.edit().putString("selected_symbol", value).apply()

    var themeMode: String
        get() = prefs.getString("theme_mode", "dark") ?: "dark"
        set(value) = prefs.edit().putString("theme_mode", value).apply()

    var retrainScheduleEnabled: Boolean
        get() = prefs.getBoolean("retrain_schedule_enabled", false)
        set(value) = prefs.edit().putBoolean("retrain_schedule_enabled", value).apply()

    var retrainIntervalHours: Int
        get() = prefs.getInt("retrain_interval_hours", 6)
        set(value) = prefs.edit().putInt("retrain_interval_hours", value.coerceAtLeast(1)).apply()

    private fun normalizeBaseUrl(value: String): String {
        val trimmed = value.trim().trimEnd('/')
        if (trimmed.isBlank()) return DEFAULT_API_BASE_URL
        return if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
            trimmed
        } else {
            "https://$trimmed"
        }
    }

    private companion object {
        const val DEFAULT_API_BASE_URL = "https://tb.kusoft.xyz"
        const val LEGACY_PI_API_BASE_URL = "http://192.168.0.185:8787"
    }
}
