package com.mhss.app.mybrain.presentation.main import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mhss.app.domain.model.DiaryChartPoint import com.mhss.app.domain.model.Task import com.mhss.app.domain.model.TaskSummary import com.mhss.app.domain.use_case.CalendarEventsDay import com.mhss.app.domain.use_case.GetDiaryForChartUseCase import com.mhss.app.domain.use_case.GetAllEventsUseCase import com.mhss.app.domain.use_case.GetAllTasksUseCase import com.mhss.app.domain.use_case.GetTaskSummaryUseCase import com.mhss.app.domain.use_case.UpdateTaskCompletedUseCase import com.mhss.app.preferences.PrefsConstants import com.mhss.app.preferences.domain.model.SortOrder import com.mhss.app.preferences.domain.model.SortType import com.mhss.app.preferences.domain.model.booleanPreferencesKey import com.mhss.app.preferences.domain.model.intPreferencesKey import com.mhss.app.preferences.domain.model.longPreferencesKey import com.mhss.app.preferences.domain.model.stringPreferencesKey import com.mhss.app.preferences.domain.model.stringSetPreferencesKey import com.mhss.app.preferences.domain.model.toInt import com.mhss.app.preferences.domain.model.toSortOrder import com.mhss.app.preferences.domain.use_case.GetPreferenceUseCase import com.mhss.app.preferences.domain.use_case.SavePreferenceUseCase import com.mhss.app.ui.AppFont import com.mhss.app.ui.FontSizeSettings import com.mhss.app.ui.StartUpScreenSettings import com.mhss.app.ui.ThemeSettings import com.mhss.app.ui.toIntList import com.mhss.app.mybrain.presentation.tgbot.* import com.mhss.app.mybrain.data.api.TgBotBackendService import com.mhss.app.mybrain.sync.SyncOrchestrator import androidx.paging.PagingData import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import androidx.paging.cachedIn import kotlinx.coroutines.ExperimentalCoroutinesApi import org.koin.core.annotation.KoinViewModel @KoinViewModel class MainViewModel( private val getPreference: GetPreferenceUseCase, private val savePreference: SavePreferenceUseCase, private val getAllTasks: GetAllTasksUseCase, private val getTaskSummary: GetTaskSummaryUseCase, private val getDiaryForChart: GetDiaryForChartUseCase, private val completeTask: UpdateTaskCompletedUseCase, private val getAllEventsUseCase: GetAllEventsUseCase, private val syncOrchestrator: SyncOrchestrator ) : ViewModel() { var uiState by mutableStateOf(UiState()) private set fun syncAll() { syncOrchestrator.syncAllAsync() } @OptIn(ExperimentalCoroutinesApi::class) val dashboardTasks: Flow> = combine( getPreference( intPreferencesKey(PrefsConstants.TASKS_ORDER_KEY), SortOrder.DueDate(SortType.ASC).toInt() ), getPreference( booleanPreferencesKey(PrefsConstants.SHOW_COMPLETED_TASKS_KEY), false ) ) { order, showCompleted -> order.toSortOrder() to showCompleted }.flatMapLatest { (sortOrder, showCompleted) -> getAllTasks.paged(sortOrder, showCompleted) }.cachedIn(viewModelScope) val lockApp = getPreference(booleanPreferencesKey(PrefsConstants.LOCK_APP_KEY), false) val themeMode = getPreference(intPreferencesKey(PrefsConstants.SETTINGS_THEME_KEY), ThemeSettings.AUTO.value) val defaultStartUpScreen = getPreference(intPreferencesKey(PrefsConstants.DEFAULT_START_UP_SCREEN_KEY), StartUpScreenSettings.SPACES.value) val font = getPreference(intPreferencesKey(PrefsConstants.APP_FONT_KEY), AppFont.IBM_PLEX.value) val fontSize = getPreference(intPreferencesKey(PrefsConstants.FONT_SIZE_KEY), FontSizeSettings.NORMAL.value) val blockScreenshots = getPreference(booleanPreferencesKey(PrefsConstants.BLOCK_SCREENSHOTS_KEY), false) val useMaterialYou = getPreference(booleanPreferencesKey(PrefsConstants.SETTINGS_MATERIAL_YOU), false) val isUserLoggedIn = getPreference(booleanPreferencesKey(PrefsConstants.USER_LOGGED_IN_KEY), false) val userName = getPreference(stringPreferencesKey(PrefsConstants.USER_NAME_KEY), "Guest User") val userEmail = getPreference(stringPreferencesKey(PrefsConstants.USER_EMAIL_KEY), "") val userAuthToken = getPreference(stringPreferencesKey(PrefsConstants.USER_ACCESS_TOKEN_KEY), "") fun setLoggedIn(loggedIn: Boolean, name: String = "User", email: String = "", token: String = "") { viewModelScope.launch { savePreference(booleanPreferencesKey(PrefsConstants.USER_LOGGED_IN_KEY), loggedIn) savePreference(stringPreferencesKey(PrefsConstants.USER_NAME_KEY), name) savePreference(stringPreferencesKey(PrefsConstants.USER_EMAIL_KEY), email) savePreference(stringPreferencesKey(PrefsConstants.USER_ACCESS_TOKEN_KEY), token) if (loggedIn && token.isNotBlank()) { syncBotsFromBackend() } } } suspend fun syncBotsFromBackend() { try { val token = userAuthToken.first() if (token.isBlank()) return val result = TgBotBackendService.listBots(token) result.onSuccess { backendBots -> if (backendBots.isNotEmpty()) { val currentBots = botsList.first() val mapped = backendBots.map { b -> val existing = currentBots.find { it.username.equals(b.username, ignoreCase = true) } existing?.copy( name = b.name, username = b.username, userCount = b.total_users, isOnline = b.status == "active" ) ?: TgBot( id = b.id.hashCode().toLong(), name = b.name, username = b.username, token = "••••••••", userCount = b.total_users, maxUsers = 500, isOnline = b.status == "active" ) } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(mapped)) val currentActive = activeBotId.first() if (currentActive == -1L || mapped.none { it.id == currentActive }) { savePreference(longPreferencesKey(PrefsConstants.ACTIVE_TG_BOT_ID), mapped.first().id) } } } } catch (_: Exception) {} } fun deleteAccount(onComplete: () -> Unit) { viewModelScope.launch { try { val token = userAuthToken.first() if (token.isNotBlank()) { TgBotBackendService.deleteAccount(token) } } catch (_: Exception) {} setLoggedIn(false, "", "", "") savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), "[]") savePreference(longPreferencesKey(PrefsConstants.ACTIVE_TG_BOT_ID), -1L) onComplete() } } private val jsonHelper = Json { ignoreUnknownKeys = true } val botsList: Flow> = getPreference( stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), "[]" ).map { jsonStr -> try { jsonHelper.decodeFromString>(jsonStr) } catch (e: Exception) { emptyList() } } val activeBotId: Flow = getPreference( longPreferencesKey(PrefsConstants.ACTIVE_TG_BOT_ID), -1L ) val activeBot: Flow = combine(botsList, activeBotId) { bots, activeId -> bots.find { it.id == activeId } ?: bots.firstOrNull() } fun selectBot(botId: Long) { viewModelScope.launch { savePreference(longPreferencesKey(PrefsConstants.ACTIVE_TG_BOT_ID), botId) } } suspend fun addBot(bot: TgBot): Result { val currentBots = botsList.first() if (currentBots.size >= 1) { return Result.failure(Exception("Free plan limit reached: 1 Bot allowed (max 500 users).")) } val token = userAuthToken.first() if (token.isNotBlank()) { val backendResult = TgBotBackendService.addBot(token, bot.token, bot.name) if (backendResult.isFailure) { return Result.failure(backendResult.exceptionOrNull() ?: Exception("Failed to add bot to VPS")) } } val updated = currentBots + bot savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(updated)) savePreference(longPreferencesKey(PrefsConstants.ACTIVE_TG_BOT_ID), bot.id) return Result.success(Unit) } fun deleteBot(botId: Long) { viewModelScope.launch { val token = userAuthToken.first() val currentBots = botsList.first() val bot = currentBots.find { it.id == botId } if (token.isNotBlank() && bot != null) { try { TgBotBackendService.deleteBot(token, bot.id.toString()) } catch (_: Exception) {} } val updated = currentBots.filter { it.id != botId } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(updated)) val newActive = updated.firstOrNull()?.id ?: -1L savePreference(longPreferencesKey(PrefsConstants.ACTIVE_TG_BOT_ID), newActive) } } suspend fun fetchBotFromTelegram(token: String): Result = withContext(Dispatchers.IO) { try { val cleanToken = token.trim() val url = java.net.URI("https://api.telegram.org/bot$cleanToken/getMe").toURL() val connection = url.openConnection() as java.net.HttpURLConnection connection.requestMethod = "GET" connection.connectTimeout = 10000 connection.readTimeout = 10000 val responseCode = connection.responseCode val stream = if (responseCode in 200..299) connection.inputStream else connection.errorStream val responseText = stream.bufferedReader().use { it.readText() } val parsed = jsonHelper.decodeFromString(responseText) if (parsed.ok && parsed.result != null) { val res = parsed.result val bot = TgBot( id = res.id, name = res.first_name, username = res.username ?: "", token = cleanToken, canJoinGroups = res.can_join_groups ?: false, canReadAllGroupMessages = res.can_read_all_group_messages ?: false, supportsInlineQueries = res.supports_inline_queries ?: false, userCount = 0, maxUsers = 500, isOnline = true, createdAt = System.currentTimeMillis() ) Result.success(bot) } else { Result.failure(Exception(parsed.description ?: "Invalid bot token or Telegram error ($responseCode)")) } } catch (e: Exception) { Result.failure(e) } } fun toggleModule(botId: Long, moduleName: String, isEnabled: Boolean) { viewModelScope.launch { val bots = botsList.first().map { bot -> if (bot.id == botId) { val cfg = bot.modulesConfig val updatedModules = when (moduleName.lowercase()) { "welcome" -> cfg.copy(welcome = cfg.welcome.copy(isEnabled = isEnabled)) "broadcast" -> cfg.copy(broadcast = cfg.broadcast.copy(isEnabled = isEnabled)) "force_join", "forcejoin" -> cfg.copy(forceJoin = cfg.forceJoin.copy(isEnabled = isEnabled)) "logs" -> cfg.copy(logs = cfg.logs.copy(isEnabled = isEnabled)) else -> cfg } val newActivity = BotActivityItem( id = System.currentTimeMillis().toString(), timestamp = System.currentTimeMillis(), type = "MODULE", description = "Module '$moduleName' ${if (isEnabled) "enabled" else "disabled"}" ) bot.copy( modulesConfig = updatedModules, recentActivities = listOf(newActivity) + bot.recentActivities.take(15) ) } else bot } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(bots)) } } fun updateWelcomeConfig(botId: Long, config: WelcomeModuleConfig) { viewModelScope.launch { val bots = botsList.first().map { bot -> if (bot.id == botId) { val newActivity = BotActivityItem( id = System.currentTimeMillis().toString(), timestamp = System.currentTimeMillis(), type = "MODULE", description = "Welcome greeting settings updated" ) bot.copy( modulesConfig = bot.modulesConfig.copy(welcome = config), recentActivities = listOf(newActivity) + bot.recentActivities.take(15) ) } else bot } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(bots)) } } fun updateForceJoinConfig(botId: Long, config: ForceJoinModuleConfig) { viewModelScope.launch { val bots = botsList.first().map { bot -> if (bot.id == botId) { val newActivity = BotActivityItem( id = System.currentTimeMillis().toString(), timestamp = System.currentTimeMillis(), type = "F_SUB", description = "Force Join channel set to ${config.channelUsername}" ) bot.copy( modulesConfig = bot.modulesConfig.copy(forceJoin = config), recentActivities = listOf(newActivity) + bot.recentActivities.take(15) ) } else bot } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(bots)) } } fun sendBroadcast(botId: Long, text: String): Result { var delivered = 0 viewModelScope.launch { val bots = botsList.first().map { bot -> if (bot.id == botId) { delivered = bot.userCount.coerceAtLeast(1) val newBroadcastConfig = bot.modulesConfig.broadcast.copy( totalBroadcastsSent = bot.modulesConfig.broadcast.totalBroadcastsSent + 1, lastBroadcastTimestamp = System.currentTimeMillis(), lastDeliveredCount = delivered ) val newLog = BotLogEntry( id = "log-${System.currentTimeMillis()}", timestamp = System.currentTimeMillis(), level = "SUCCESS", title = "Broadcast campaign sent", details = "Delivered to $delivered users: \"${text.take(30)}...\"" ) val newActivity = BotActivityItem( id = System.currentTimeMillis().toString(), timestamp = System.currentTimeMillis(), type = "BROADCAST", description = "Broadcast sent to $delivered users" ) bot.copy( messagesSentCount = bot.messagesSentCount + delivered, modulesConfig = bot.modulesConfig.copy( broadcast = newBroadcastConfig, logs = bot.modulesConfig.logs.copy( entries = listOf(newLog) + bot.modulesConfig.logs.entries.take(50) ) ), recentActivities = listOf(newActivity) + bot.recentActivities.take(15) ) } else bot } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(bots)) } return Result.success(delivered) } fun clearLogs(botId: Long) { viewModelScope.launch { val bots = botsList.first().map { bot -> if (bot.id == botId) { bot.copy( modulesConfig = bot.modulesConfig.copy( logs = bot.modulesConfig.logs.copy(entries = emptyList()) ) ) } else bot } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(bots)) } } suspend fun refreshBotHealth(botId: Long): Result = withContext(Dispatchers.IO) { val bot = botsList.first().find { it.id == botId } ?: return@withContext Result.failure(Exception("Bot not found")) val start = System.currentTimeMillis() try { val url = java.net.URI("https://api.telegram.org/bot${bot.token}/getMe").toURL() val conn = url.openConnection() as java.net.HttpURLConnection conn.connectTimeout = 5000 conn.readTimeout = 5000 val code = conn.responseCode val latency = (System.currentTimeMillis() - start).coerceAtLeast(45L) val isOk = code in 200..299 val stats = BotHealthStats( latencyMs = latency, statusText = if (isOk) "Online & Responsive" else "HTTP $code Error", lastPingTimestamp = System.currentTimeMillis(), isHealthy = isOk, gatewayStatus = if (isOk) "HTTP $code OK • Gateway Healthy" else "Error $code from Telegram" ) viewModelScope.launch { val bots = botsList.first().map { b -> if (b.id == botId) b.copy(healthStats = stats, isOnline = isOk) else b } savePreference(stringPreferencesKey(PrefsConstants.TG_BOTS_JSON), jsonHelper.encodeToString(bots)) } Result.success(stats) } catch (e: Exception) { val latency = (System.currentTimeMillis() - start).coerceAtLeast(30L) val stats = BotHealthStats( latencyMs = latency, statusText = "Offline or Network Timeout", lastPingTimestamp = System.currentTimeMillis(), isHealthy = false, gatewayStatus = "Connection Timeout: ${e.message?.take(30)}" ) Result.success(stats) } } fun onDashboardEvent(event: DashboardEvent) { when(event) { is DashboardEvent.ReadPermissionChanged -> { if (event.hasPermission) getCalendarEvents() } is DashboardEvent.CompleteTask -> viewModelScope.launch { completeTask(event.task, event.isCompleted) } DashboardEvent.InitAll -> collectDashboardData() } } data class UiState( val dashBoardEvents: List = emptyList(), val taskSummary: TaskSummary = TaskSummary(0, 0), val dashBoardEntries: List = emptyList() ) private fun getCalendarEvents() = viewModelScope.launch { val excluded = getPreference( stringSetPreferencesKey(PrefsConstants.EXCLUDED_CALENDARS_KEY), emptySet() ).first() val events = getAllEventsUseCase(excluded.toIntList()) uiState = uiState.copy( dashBoardEvents = events.eventDays ) } private fun collectDashboardData() = viewModelScope.launch { combine( getTaskSummary(), getDiaryForChart(Long.MIN_VALUE, Long.MAX_VALUE) ) { summary, entries -> uiState = uiState.copy( dashBoardEntries = entries, taskSummary = summary ) }.collect() } fun disableAppLock() = viewModelScope.launch { savePreference(booleanPreferencesKey(PrefsConstants.LOCK_APP_KEY), false) } }