package swiss.qpq.gajumobile.data

import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString
import java.io.File

@Serializable
data class AppState(
    val unverifiedAccountIds: Set<String> = emptySet(),
    val lastPesteredAt: Long = 0L,
    val balanceFormat: String = "US",
    val balanceUnit: String = "GAJU",
    val walletsVersion: Int = 0 // Incremented on wallet changes to trigger UI updates
)

class AppStateManager(context: Context) {
    private val json = Json { prettyPrint = true }
    private val stateFile = File(context.filesDir, "app_state.json")
    
    private val _state = MutableStateFlow(loadStateFromFile())
    val state: StateFlow<AppState> = _state.asStateFlow()

    private fun loadStateFromFile(): AppState {
        return if (stateFile.exists()) {
            try {
                json.decodeFromString(stateFile.readText())
            } catch (_: Exception) {
                AppState()
            }
        } else {
            AppState()
        }
    }

    fun saveState(state: AppState) {
        stateFile.writeText(json.encodeToString(state))
        _state.value = state
    }

    fun markUnverified(accountId: String) {
        val current = _state.value
        saveState(current.copy(unverifiedAccountIds = current.unverifiedAccountIds + accountId))
    }

    fun clearVerified(accountId: String) {
        val current = _state.value
        saveState(current.copy(unverifiedAccountIds = current.unverifiedAccountIds - accountId))
    }

    fun setBalanceFormat(format: String) {
        val current = _state.value
        saveState(current.copy(balanceFormat = format))
    }

    fun setBalanceUnit(unit: String) {
        val current = _state.value
        saveState(current.copy(balanceUnit = unit))
    }

    fun notifyWalletsChanged() {
        val current = _state.value
        saveState(current.copy(walletsVersion = current.walletsVersion + 1))
    }
}
