import Foundation
import Testing
@testable import Workouts

/// Locks the survivor rules of `DuplicateCleanupPlanner` — the safety-critical
/// part of the developer duplicate-cleanup tool. Referenced-routine and seed
/// protection must always beat "earliest ULID wins," an in-progress workout must
/// never be touched, and the HealthKit-link holder must always survive (deleting
/// it would cascade-delete the real Health sample). Fixed 26-char ULID-like ids
/// keep every assertion deterministic.
struct DuplicateCleanupPlannerTests {

    // MARK: - Fixtures

    private func id(_ n: Int) -> String {
        "01TESTID" + String(repeating: "0", count: 16) + String(format: "%02d", n)
    }

    private func exercise(
        name: String = "Bench Press", order: Int = 0, sets: Int = 3, reps: Int = 10,
        weight: Double = 100, loadType: Int = LoadType.weight.rawValue, duration: Int = 0
    ) -> ExerciseDocument {
        ExerciseDocument(
            id: "EX-\(name)-\(order)", name: name, order: order, sets: sets, reps: reps, weight: weight,
            loadType: loadType, durationSeconds: duration
        )
    }

    private func routine(
        id routineID: String, name: String = "Push Day", exercises: [ExerciseDocument]? = nil,
        createdAt: Date = Date(timeIntervalSince1970: 0)
    ) -> RoutineDocument {
        RoutineDocument(
            schemaVersion: RoutineDocument.currentSchemaVersion, id: routineID, name: name, color: "indigo",
            systemImage: "dumbbell.fill", order: 0, createdAt: createdAt, updatedAt: createdAt,
            exercises: exercises ?? [exercise()], activityType: nil
        )
    }

    private func log(name: String = "Bench Press", order: Int = 0, date: Date = Date(timeIntervalSince1970: 0)) -> WorkoutLogDocument {
        WorkoutLogDocument(
            id: "LOG-\(name)-\(order)", exerciseName: name, order: order, sets: 3, reps: 10, weight: 100,
            loadType: LoadType.weight.rawValue, durationSeconds: 0, currentStateIndex: 0,
            status: WorkoutStatus.completed.rawValue, notes: nil, date: date
        )
    }

    private func workout(
        id workoutID: String, routineID: String? = "RT-1", routineName: String? = "Push Day",
        start: Date, status: String = WorkoutStatus.completed.rawValue,
        logs: [WorkoutLogDocument]? = nil, metrics: WorkoutMetrics? = nil
    ) -> WorkoutDocument {
        WorkoutDocument(
            schemaVersion: WorkoutDocument.currentSchemaVersion, id: workoutID, routineID: routineID,
            routineName: routineName, start: start, end: nil, status: status, createdAt: start, updatedAt: start,
            logs: logs ?? [log(date: start)], metrics: metrics
        )
    }

    /// A fixed calendar day/time built via `Calendar.current`, so it agrees with
    /// the planner's own `Calendar.current`-based day bucketing regardless of the
    /// test runner's time zone.
    private func fixedDate(day: Int = 15, hour: Int = 9) -> Date {
        var comps = DateComponents()
        comps.year = 2024
        comps.month = 3
        comps.day = day
        comps.hour = hour
        return Calendar.current.date(from: comps)!
    }

    private func metrics(healthKitWorkoutUUID: String? = nil, recordedAt: Date = Date(timeIntervalSince1970: 0)) -> WorkoutMetrics {
        WorkoutMetrics(
            activeEnergyKcal: nil, avgHeartRate: nil, maxHeartRate: nil, minHeartRate: nil,
            totalVolume: nil, hrZoneSeconds: nil, healthKitWorkoutUUID: healthKitWorkoutUUID,
            source: .watch, recordedAt: recordedAt
        )
    }

    // MARK: - Routine survivor rules

    @Test func identicalUnreferencedRoutinesKeepEarliestULID() {
        let earlier = routine(id: id(1))
        let later = routine(id: id(2))
        let plan = DuplicateCleanupPlanner.plan(
            routines: [later, earlier], workouts: [], referencedRoutineIDs: [], isSeed: { _ in false }
        )
        #expect(plan.routineGroups.count == 1)
        #expect(plan.routineGroups[0].keep.map(\.id) == [id(1)])
        #expect(plan.routineGroups[0].delete.map(\.id) == [id(2)])
    }

    /// Referenced-protection must override "earliest ULID wins": a later,
    /// referenced routine survives and the earlier, unreferenced duplicate is the
    /// one deleted — the opposite of the no-protection tiebreak.
    @Test func referencedProtectionOverridesEarliestWins() {
        let earlier = routine(id: id(1)) // unreferenced, would win the earliest-id tiebreak alone
        let later = routine(id: id(2))   // referenced by a workout
        let plan = DuplicateCleanupPlanner.plan(
            routines: [earlier, later], workouts: [], referencedRoutineIDs: [id(2)], isSeed: { _ in false }
        )
        #expect(plan.routineGroups.count == 1)
        #expect(plan.routineGroups[0].keep.map(\.id) == [id(2)])
        #expect(plan.routineGroups[0].delete.map(\.id) == [id(1)])
    }

    @Test func seedMemberNeverDeleted() throws {
        let seedRoutine = routine(id: id(1))
        let duplicate = routine(id: id(2))
        let plan = DuplicateCleanupPlanner.plan(
            routines: [seedRoutine, duplicate], workouts: [], referencedRoutineIDs: [],
            isSeed: { $0 == id(1) }
        )
        let group = try #require(plan.routineGroups.first)
        #expect(group.keep.map(\.id) == [id(1)])
        #expect(group.delete.map(\.id) == [id(2)])
        #expect(!group.delete.contains { $0.id == id(1) })
    }

    @Test func differingExerciseContentNotGrouped() {
        let a = routine(id: id(1), exercises: [exercise(weight: 100)])
        let b = routine(id: id(2), exercises: [exercise(weight: 105)])
        let plan = DuplicateCleanupPlanner.plan(
            routines: [a, b], workouts: [], referencedRoutineIDs: [], isSeed: { _ in false }
        )
        #expect(plan.routineGroups.isEmpty)
    }

    /// Machine comfort settings are real content: routines identical except for a
    /// setting value — or for the nil (non-machine) vs. empty (machine, nothing
    /// recorded) distinction — must not be judged duplicates.
    @Test func differingMachineSettingsNotGrouped() {
        var lowSeat = exercise()
        lowSeat.machineSettings = [MachineSetting(name: "Seat Height", value: "4")]
        var highSeat = exercise()
        highSeat.machineSettings = [MachineSetting(name: "Seat Height", value: "5")]
        var machineNothingRecorded = exercise()
        machineNothingRecorded.machineSettings = []

        let a = routine(id: id(1), exercises: [lowSeat])
        let b = routine(id: id(2), exercises: [highSeat])
        let c = routine(id: id(3), exercises: [machineNothingRecorded])
        let d = routine(id: id(4)) // machineSettings nil — not a machine exercise
        let plan = DuplicateCleanupPlanner.plan(
            routines: [a, b, c, d], workouts: [], referencedRoutineIDs: [], isSeed: { _ in false }
        )
        #expect(plan.routineGroups.isEmpty)
    }

    // MARK: - Workout grouping / survivor rules

    @Test func sameDayWorkoutsDifferingOnlyInIDsAndTimestampsAreGrouped() {
        let day = fixedDate(hour: 9)
        let sameDayLater = fixedDate(hour: 20)
        let w1 = workout(id: id(1), start: day)
        let w2 = workout(id: id(2), start: sameDayLater)
        let plan = DuplicateCleanupPlanner.plan(
            routines: [], workouts: [w1, w2], referencedRoutineIDs: [], isSeed: { _ in false }
        )
        #expect(plan.workoutGroups.count == 1)
        #expect(plan.workoutGroups[0].keep.id == id(1))
        #expect(plan.workoutGroups[0].delete.map(\.id) == [id(2)])
    }

    @Test func differentDaysNotGrouped() {
        let w1 = workout(id: id(1), start: fixedDate(day: 15))
        let w2 = workout(id: id(2), start: fixedDate(day: 16))
        let plan = DuplicateCleanupPlanner.plan(
            routines: [], workouts: [w1, w2], referencedRoutineIDs: [], isSeed: { _ in false }
        )
        #expect(plan.workoutGroups.isEmpty)
    }

    @Test func inProgressMemberDropsEntireGroup() {
        let start = fixedDate()
        let w1 = workout(id: id(1), start: start, status: WorkoutStatus.inProgress.rawValue)
        let w2 = workout(id: id(2), start: start, status: WorkoutStatus.inProgress.rawValue)
        let plan = DuplicateCleanupPlanner.plan(
            routines: [], workouts: [w1, w2], referencedRoutineIDs: [], isSeed: { _ in false }
        )
        #expect(plan.workoutGroups.isEmpty)
    }

    /// The HealthKit-link holder must survive even though the other copy has the
    /// lexicographically smaller (earlier) id — deleting the link holder would
    /// cascade-delete the real Health sample.
    @Test func healthKitLinkHolderSurvivesOverEarlierULID() throws {
        let start = fixedDate()
        let earlierNoLink = workout(id: id(1), start: start, metrics: nil)
        let laterWithLink = workout(id: id(2), start: start, metrics: metrics(healthKitWorkoutUUID: "HK-UUID"))
        let plan = DuplicateCleanupPlanner.plan(
            routines: [], workouts: [earlierNoLink, laterWithLink], referencedRoutineIDs: [], isSeed: { _ in false }
        )
        let group = try #require(plan.workoutGroups.first)
        #expect(group.keep.id == id(2))
        #expect(group.delete.map(\.id) == [id(1)])
    }
}
