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 = ""
    var localSequenceNumber: Int = 0
    var previousSnapshotID: UUID?
    var isChainStart: Bool = false
    var recoveredDeviceID: Bool = false
    var snapshotQualityRaw: String = SnapshotQuality.complete.rawValue
    var anomalyFlagsJSON: String = "[]"
    var triggerReason: String = "manual"
    var retryOfSnapshotID: UUID?
    var isPostRestore: Bool = false
    var isPostRestoreInferred: Bool = false
    var isPostRestoreSuppressedDeltaID: UUID?
    var hardwareModel: String = ""
    var appBuildVersion: String = ""
    var monitoredTypeSetHash: String = ""
    var monitoredRegistryVersion: Int = 0
    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 snapshotQuality: SnapshotQuality {
        get { SnapshotQuality(rawValue: snapshotQualityRaw) ?? .complete }
        set { snapshotQualityRaw = newValue.rawValue }
    }

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