package com.omixlab.lckcontrol.ui.cortex

import android.os.StatFs
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.omixlab.lckcontrol.cortex.CortexManager
import com.omixlab.lckcontrol.cortex.CortexPreferences
import com.omixlab.lckcontrol.cortex.CortexSession
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject

@HiltViewModel
class CortexViewModel @Inject constructor(
    private val cortexManager: CortexManager,
    private val cortexPreferences: CortexPreferences,
) : ViewModel() {

    val sessions: StateFlow<List<CortexSession>> = cortexManager.sessions
    val isRecording: StateFlow<Boolean> = cortexManager.isRecording
    val storageUsedBytes: StateFlow<Long> = cortexManager.storageUsedBytes

    private val _isEnabled = MutableStateFlow(cortexPreferences.isEnabled())
    val isEnabled: StateFlow<Boolean> = _isEnabled.asStateFlow()

    private val _maxMinutes = MutableStateFlow(cortexPreferences.getMaxMinutes())
    val maxMinutes: StateFlow<Int> = _maxMinutes.asStateFlow()

    init {
        cortexManager.refreshSessions()
    }

    fun setEnabled(enabled: Boolean) {
        cortexPreferences.setEnabled(enabled)
        _isEnabled.value = enabled
    }

    fun setMaxMinutes(minutes: Int) {
        cortexPreferences.setMaxMinutes(minutes)
        _maxMinutes.value = minutes
    }

    fun deleteSession(sessionId: String) {
        viewModelScope.launch {
            cortexManager.deleteSession(sessionId)
        }
    }

    fun deleteAllSessions() {
        viewModelScope.launch {
            cortexManager.deleteAllSessions()
        }
    }

    fun getAvailableStorageBytes(): Long {
        return try {
            val stat = StatFs(File("/data").absolutePath)
            stat.availableBlocksLong * stat.blockSizeLong
        } catch (_: Exception) {
            0L
        }
    }
}
