import Foundation
import SwiftData

@Model
final class HealthSnapshot {
    @Attribute(.unique) var id: UUID
    @Attribute var timestamp: Date
    @Attribute var osVersion: String
    @Attribute var deviceName: String
    @Attribute var deviceID: String
    @Attribute var localSequenceNumber: Int
    @Attribute var previousSnapshotID: UUID?
    @Attribute var isChainStart: Bool
    @Attribute var recoveredDeviceID: Bool
    @Attribute var snapshotQuality: SnapshotQuality
    @Attribute var anomalyFlagsJSON: String
    @Attribute var triggerReason: String
    @Attribute var isPostRestore: Bool
    @Attribute var isPostRestoreInferred: Bool
    @Attribute var isPostRestoreSuppressedDeltaID: UUID?
    @Attribute var hardwareModel: String
    @Attribute var appBuildVersion: String
    @Attribute var monitoredTypeSetHash: String
    @Attribute var monitoredRegistryVersion: Int
    @Attribute 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.localSequenceNumber = 0
        self.previousSnapshotID = nil
        self.isChainStart = false
        self.recoveredDeviceID = false
        self.snapshotQuality = .complete
        self.anomalyFlagsJSON = "[]"
        self.triggerReason = "manual"
        self.isPostRestore = false
        self.isPostRestoreInferred = false
        self.isPostRestoreSuppressedDeltaID = nil
        self.hardwareModel = ""
        self.appBuildVersion = ""
        self.monitoredTypeSetHash = ""
        self.monitoredRegistryVersion = 0
        self.yearlyCountTimezoneIdentifier = ""
        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)) ?? "[]" }
    }
}
