package com.peachpasswords.ui.sync import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.peachpasswords.sync.ChirpSyncVaultAdapter import com.peachpasswords.sync.SyncEndpoint import com.peachpasswords.sync.SyncOutcomeStatus import com.peachpasswords.sync.SyncStatus import com.peachpasswords.sync.VaultSyncAdapter import com.peachpasswords.sync.deriveSyncIdentityKeypair import com.peachpasswords.sync.getOrCreateDeviceId import com.peachpasswords.sync.openChirpSyncSession import com.peachpasswords.sync.runChirpSyncInitiator import com.peachpasswords.vault.VaultCrypto import com.peachpasswords.vault.VaultRepository import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject /** * Drives a Chirp Sync round and surfaces its status to the Sync settings card. * * Trigger conditions (browser `sync-trigger.ts` parity): * 1. Vault mutation — a local add/update/delete should schedule a sync. * 2. App foreground — reconnect to nearby peers on resume. * 3. Manual — the "Sync now" control on the Sync card. * 4. mDNS peer discovery — a paired device appears on the LAN. * * Discovery, the WebSocket server role, and the paired-device store land with * the pairing UI (Phase 10); [syncWith] already performs a real initiator round * against a known endpoint so those wirings have a finished target to call. */ @HiltViewModel class SyncViewModel @Inject constructor( @ApplicationContext private val context: Context, private val vault: VaultRepository, ) : ViewModel() { private val _status = MutableStateFlow(SyncStatus.Idle) val status: StateFlow = _status.asStateFlow() /** Adapter over the live vault; null while the vault is locked. */ fun buildAdapter(): ChirpSyncVaultAdapter? { if (!vault.isUnlocked.value) return null return VaultSyncAdapter(vault, getOrCreateDeviceId(context)) } /** * Manual / discovery trigger. With no paired-device store yet, this reports * Offline when there is nothing to dial; pairing (Phase 10) supplies peers. */ fun triggerSync() { if (!vault.isUnlocked.value) { _status.value = SyncStatus.Error("vault_locked") return } // No paired-device registry on Android yet — nothing reachable to dial. _status.value = SyncStatus.Offline } /** Run one initiator round against a known peer endpoint. */ fun syncWith(endpoint: SyncEndpoint, expectedRemotePubkeyHex: String) { val master = vault.syncMasterKey() ?: run { _status.value = SyncStatus.Error("vault_locked") return } val adapter = buildAdapter() ?: run { _status.value = SyncStatus.Error("vault_locked") master.fill(0) return } _status.value = SyncStatus.Syncing viewModelScope.launch { try { val deviceId = getOrCreateDeviceId(context) val identity = deriveSyncIdentityKeypair(master, deviceId) val session = openChirpSyncSession( endpoint = endpoint, ourLongTermPrivateKey = identity.secretKey, ourLongTermPublicKey = identity.publicKey, expectedRemotePubkeyHex = expectedRemotePubkeyHex, ) val outcome = try { runChirpSyncInitiator(session, adapter) } finally { session.close() } _status.value = when (outcome.status) { SyncOutcomeStatus.COMPLETED -> SyncStatus.LastSynced(System.currentTimeMillis()) SyncOutcomeStatus.VAULT_MISMATCH -> SyncStatus.Error("vault_id_mismatch") SyncOutcomeStatus.TIMEOUT -> SyncStatus.Error("timeout") SyncOutcomeStatus.ERRORED -> SyncStatus.Error(outcome.error ?: "sync_failed") } } catch (e: Exception) { _status.value = SyncStatus.Error(e.message ?: "sync_failed") } finally { VaultCrypto.zero(master) } } } }