/*
 * Copyright (c) 2026 QPQ IaaS AG <info@qpq.swiss>. All rights reserved.
 * Project: Gajumaru Core Java Libraries <gajumaru.io>
 *
 * This program is dual-licensed:
 * 1) Under the GNU Affero General Public License as published by the Free
 *    Software Foundation, either version 3 of the License, or (at your option)
 *    any later version (AGPL-3.0-or-later).
 *
 * 2) Under a commercial/proprietary license available directly from QPQ IaaS AG.
 *    If you wish to use this software outside the strict constraints of the
 *    AGPLv3 (e.g. within a closed-source or proprietary product), you must
 *    purchase a commercial license from QPQ IaaS AG.
 *
 * Authors:
 *   - Craig Everett <craigeverett@qpq.swiss>
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-QPQ-Commercial
 */

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))
    }
}
