package com.doctate.watch.domain

import android.util.Log
import com.doctate.watch.audio.PendingCleanup
import java.io.File

/**
 * One-shot startup cleanup. Mirrors `doctate-desktop::startup`.
 *
 * Two retention horizons: 72 h for synced markers (non-sensitive UUIDs +
 * oneliners), 24 h for orphan audio in the pending queue (sensitive). The
 * watch is a "sophisticated microphone" — it must not hoard recordings
 * that never reached the server past the dictation-day horizon.
 *
 * Best-effort: failures are logged, never thrown. A failing sweep
 * shouldn't stop the watch from starting.
 */
object StartupCleanup {
    private const val TAG = "StartupCleanup"

    /** 72 hours — long enough to span a weekend, short enough to limit data exposure. */
    const val DEFAULT_MARKER_RETENTION_MS: Long = 72L * 3600L * 1000L

    /** 24 hours — orphan recordings older than yesterday are presumed lost. */
    const val DEFAULT_ORPHAN_AUDIO_RETENTION_MS: Long = 24L * 3600L * 1000L

    suspend fun run(
        store: CaseStore,
        pendingDir: File,
        nowMs: Long = System.currentTimeMillis(),
        markerRetentionMs: Long = DEFAULT_MARKER_RETENTION_MS,
        orphanAudioRetentionMs: Long = DEFAULT_ORPHAN_AUDIO_RETENTION_MS,
    ) {
        try {
            val markerCutoff = nowMs - markerRetentionMs
            val n = store.cleanupStale(markerCutoff)
            if (n > 0) Log.i(TAG, "startup: stale markers removed: $n")
        } catch (e: Exception) {
            Log.w(TAG, "startup: marker sweep failed: ${e.message}")
        }

        try {
            val audioCutoff = nowMs - orphanAudioRetentionMs
            val n = PendingCleanup.cleanupOrphanAudio(pendingDir, audioCutoff)
            if (n > 0) Log.i(TAG, "startup: orphan audio removed: $n")
        } catch (e: Exception) {
            Log.w(TAG, "startup: orphan-audio sweep failed: ${e.message}")
        }
    }
}
