//
// WorkoutMergePlanner.swift
// Workouts
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//

import Foundation

/// Pure, deterministic per-log merge of a watch-pushed `WorkoutDocument` against the phone's
/// cached copy — the durable fix for H1, where `ingestFromWatch` arbitrated by *whole-document*
/// `updatedAt` and so lost one side's edit whenever the two devices changed the same workout at
/// once. Merging per log makes edits to *different* exercises commute: neither side is clobbered
/// just because its overall stamp is newer, so delivery order and offline gaps stop mattering.
///
/// Log existence is reconciled by id against explicit deletion tombstones (`deletedLogIDs`,
/// phone-authored — the watch never deletes a log), so an absent log is never ambiguous between
/// "deleted on the phone" and "just added on the watch". Runs phone-side only (in
/// `SyncEngine.ingestFromWatch`); the merged document then flows through the normal
/// `save(workout:)` path and is echoed authoritatively back to the watch.
enum WorkoutMergePlanner {
    /// Deletion tombstones older than this are pruned. A device offline longer than the grace
    /// may resurrect a since-deleted log — the same bounded risk as the whole-workout stub grace.
    static let tombstoneGrace: TimeInterval = 30 * 24 * 60 * 60

    /// The instant a log was last changed, for ordering concurrent edits: its own `updatedAt`
    /// when present, else the best lifecycle timestamp, else `.distantPast` — so a legacy log
    /// carrying no stamp always loses to a stamped edit and to any tombstone.
    static func modTime(_ log: WorkoutLogDocument) -> Date {
        log.updatedAt ?? log.completedAt ?? log.startedAt ?? .distantPast
    }

    /// Merge `incoming` (from the watch) into `cached` (the phone's current copy). Log content
    /// is resolved per id (newer `modTime` wins); deletion tombstones from both sides union and
    /// drop a log only when the deletion is at-or-after the log's own edit — a strictly-newer
    /// edit resurrects the log and clears its stale tombstone. Workout-level scalars come from
    /// whichever document is newer overall; status and `end` are recomputed from the merged logs.
    static func merge(incoming: WorkoutDocument, cached: WorkoutDocument, now: Date = Date()) -> WorkoutDocument {
        // 1. Union deletion tombstones — newest stamp per id wins.
        var tombstones = cached.deletedLogIDs ?? [:]
        for (id, when) in incoming.deletedLogIDs ?? [:] {
            tombstones[id] = tombstones[id].map { max($0, when) } ?? when
        }

        // 2. Per-id log union — newer modTime wins; equal stamps keep the cached (phone) copy.
        var logsByID: [String: WorkoutLogDocument] = [:]
        for log in cached.logs { logsByID[log.id] = log }
        for log in incoming.logs {
            guard let have = logsByID[log.id] else { logsByID[log.id] = log; continue }
            if modTime(log) > modTime(have) { logsByID[log.id] = log }
        }

        // 3. Apply tombstones: a deletion at-or-after the log's own edit drops it; a strictly
        //    newer edit resurrects the log and clears the now-stale tombstone.
        for (id, deletedAt) in tombstones {
            guard let log = logsByID[id] else { continue }
            if modTime(log) > deletedAt {
                tombstones.removeValue(forKey: id)
            } else {
                logsByID.removeValue(forKey: id)
            }
        }

        // 4. Prune tombstones past the grace period.
        tombstones = tombstones.filter { now.timeIntervalSince($0.value) < tombstoneGrace }

        // 5. Base scalars (routineID/name, start, metrics, …) on the newer document overall — it
        //    carries a just-attached metrics summary or a rename — then override the reconciled
        //    parts. Ties prefer the cached copy (the phone is the sole writer). Sort is
        //    id-tie-broken so the result is deterministic even when two logs share an `order`.
        var merged = incoming.updatedAt > cached.updatedAt ? incoming : cached
        merged.logs = logsByID.values.sorted {
            $0.order != $1.order ? $0.order < $1.order : $0.id < $1.id
        }
        merged.deletedLogIDs = tombstones.isEmpty ? nil : tombstones
        merged.recomputeStatusFromLogs(now: now)
        merged.updatedAt = max(incoming.updatedAt, cached.updatedAt)
        merged.schemaVersion = WorkoutDocument.currentSchemaVersion
        return merged
    }
}
