import Foundation
import SwiftData

@Model
final class HealthSnapshot {
    var id: UUID = UUID()
    var timestamp: Date = Date.now
    var osVersion: String = ""
    var deviceName: String = ""
    var deviceID: String = ""

    // Chain linkage
    // localSequenceNumber is UI/debug only — used ONLY during local snapshot creation to find
    // the latest local candidate. Never use this for chain reconstruction; use previousSnapshotID.
    var localSequenceNumber: Int = 0
    var previousSnapshotID: UUID? = nil  // sole source of chain truth — all reconstruction uses this
    var isChainStart: Bool = false
    var recoveredDeviceID: Bool = false  // true when DB was wiped but Keychain had a deviceID

    // Quality
    var snapshotQuality: SnapshotQuality = SnapshotQuality.complete
    var anomalyFlagsJSON: String = "[]"  // JSON-encoded [String] — CloudKit-safe array storage

    // Trigger context
    var triggerReason: String = "manual"  // "manual" | "observerCallback" | "backgroundRefresh"
    var isPostRestore: Bool = false
    // isPostRestore suppression: forwarded past low-quality successors until consumed by a .complete delta
    var isPostRestoreInferred: Bool = false
    var isPostRestoreSuppressedDeltaID: UUID? = nil  // set to the deltaID that consumed the suppression token

    // Device identity — informational only, never used for chain linkage
    var hardwareModel: String = ""
    var appBuildVersion: String = ""

    // Registry fingerprint — used to suppress false anomalies from type set changes
    var monitoredTypeSetHash: String = ""
    var monitoredRegistryVersion: Int = 0

    // Timezone context — used by DeltaService to suppress false YearlyCount deltas across timezone changes
    var yearlyCountTimezoneIdentifier: String = ""

    @Relationship(deleteRule: .cascade, inverse: \TypeCount.snapshot)
    var typeCounts: [TypeCount]?

    init(
        timestamp: Date,
        osVersion: String,
        deviceName: String,
        deviceID: String
    ) {
        self.id = UUID()
        self.timestamp = timestamp
        self.osVersion = osVersion
        self.deviceName = deviceName
        self.deviceID = deviceID
        self.typeCounts = []
    }
}

extension HealthSnapshot {
    var anomalyFlags: [String] {
        get { (try? JSONDecoder().decode([String].self, from: Data(anomalyFlagsJSON.utf8))) ?? [] }
        set { anomalyFlagsJSON = (try? String(data: JSONEncoder().encode(newValue), encoding: .utf8)) ?? "[]" }
    }
}
