package com.doctate.watch.audio

import android.util.Log
import java.io.File

/**
 * Reap orphan artefacts in [pendingDir]. Mirrors
 * `doctate-desktop::pending_cleanup::cleanup_orphan_audio`.
 *
 * "Orphan" = an `.m4a` without sidecar (or vice versa) older than
 * [ageCutoffMs]. Atomic-write leftovers (`.tmp` files) bypass the cutoff
 * — at app startup they cannot be in-progress work; the watch is single-
 * process per user.
 *
 * Returns the count of deleted files. Best-effort: failures are logged
 * and skipped, never thrown — a missing-permissions or read-only-fs
 * surprise must not stop the watch from starting.
 */
object PendingCleanup {
    private const val TAG = "PendingCleanup"

    fun cleanupOrphanAudio(pendingDir: File, ageCutoffMs: Long): Int {
        if (!pendingDir.exists() || !pendingDir.isDirectory) return 0
        val files = pendingDir.listFiles() ?: return 0
        val names = files.map { it.name }.toHashSet()
        var deleted = 0

        for (file in files) {
            val name = file.name

            // Tmp leftovers: always remove, no age check.
            if (name.endsWith(".m4a.tmp") || name.endsWith(".meta.json.tmp")) {
                if (file.delete()) {
                    Log.i(TAG, "tmp leftover removed: $name")
                    deleted++
                } else {
                    Log.w(TAG, "failed to remove tmp leftover: $name")
                }
                continue
            }

            // Orphan m4a: no sidecar present.
            if (name.endsWith(".m4a")) {
                val stem = name.removeSuffix(".m4a")
                val sibling = "$stem.meta.json"
                if (sibling in names) continue
                if (file.lastModified() < ageCutoffMs) {
                    if (file.delete()) {
                        Log.i(TAG, "orphan m4a removed (no sidecar): $name")
                        deleted++
                    } else {
                        Log.w(TAG, "failed to remove orphan m4a: $name")
                    }
                }
                continue
            }

            // Orphan sidecar: no audio present.
            if (name.endsWith(".meta.json")) {
                val stem = name.removeSuffix(".meta.json")
                val sibling = "$stem.m4a"
                if (sibling in names) continue
                if (file.lastModified() < ageCutoffMs) {
                    if (file.delete()) {
                        Log.i(TAG, "orphan sidecar removed (no m4a): $name")
                        deleted++
                    } else {
                        Log.w(TAG, "failed to remove orphan sidecar: $name")
                    }
                }
            }
        }
        return deleted
    }
}
