import Foundation
import SwiftData

// Interface updated 2026-05-17 — see AGENTS.md
@Model final class TypeCount {
    var id: UUID = UUID()
    var typeIdentifier: String = ""
    var displayName: String = ""
    var count: Int = 0
    var contentHash: String = ""
    var earliestDate: Date?
    var latestDate: Date?
    var qualityRaw: String = SnapshotQuality.complete.rawValue
    var isUnsupported: Bool = false
    var contentEquivalentTypeCountID: UUID?
    @Attribute(.externalStorage) var recordArchiveData: Data?
    @Attribute(.externalStorage) var detailCacheData: Data?
    var snapshot: HealthSnapshot?
    @Relationship(deleteRule: .cascade, inverse: \YearlyCount.typeCount)
    var yearlyCounts: [YearlyCount]? = []
    @Relationship(deleteRule: .cascade, inverse: \HealthRecord.typeCount)
    var records: [HealthRecord]? = []
    @Relationship(deleteRule: .cascade, inverse: \TypeDistributionBin.typeCount)
    var distributionBins: [TypeDistributionBin]? = []

    init(typeIdentifier: String, displayName: String, count: Int, quality: SnapshotQuality = .complete) {
        self.id = UUID()
        self.typeIdentifier = typeIdentifier
        self.displayName = displayName
        self.count = count
        self.qualityRaw = quality.rawValue
    }
}

extension TypeCount {
    var quality: SnapshotQuality {
        get { SnapshotQuality(rawValue: qualityRaw) ?? .complete }
        set { qualityRaw = newValue.rawValue }
    }

    var recordValues: [HealthRecordValue] {
        if let recordArchiveData,
           let decoded = HealthRecordArchive.decode(recordArchiveData) {
            return decoded
        }

        return []
    }

    func setRecordValues(_ values: [HealthRecordValue]) {
        recordArchiveData = HealthRecordArchive.encode(values)
        records?.removeAll()
    }

    @MainActor var detailCache: TypeCountDetailCache? {
        guard let detailCacheData else { return nil }
        return TypeCountDetailCacheArchive.decode(detailCacheData)
    }

    @MainActor func setDetailCache(_ cache: TypeCountDetailCache?) {
        detailCacheData = cache.flatMap(TypeCountDetailCacheArchive.encode)
    }

    var isContentAlias: Bool {
        contentEquivalentTypeCountID != nil
    }

    var contentRepresentativeTypeCountID: UUID {
        contentEquivalentTypeCountID ?? id
    }
}
