import Foundation

// Per-UTC-day reload counter, shared by every widget in the
// HalflightWidgets bundle. The watch app's `AppGroupCache` exposes a
// matching reader (`todaysReloadAudit()` / `todaysLatestMediaReloadAudit()`)
// for the AccountView debug section, which reads but never writes —
// the writers live in this target.
//
// Apple's documented widget timeline reload budget is "around 40 to
// 70 per day on watchOS" (see "Keeping a widget up to date"). The
// counter rolls over per UTC day so the watch app can show "N
// reloads today" without time-window math of its own.

enum ComplicationAudit {
    static let appGroupSuiteName = "group.ht.halflig.app"

    struct Record: Codable {
        var utcDay: String
        var count: Int
    }

    /// Bump the counter at `key` for today's UTC day and return the
    /// new count. The shape is `{utcDay, count}`; rolling over to a
    /// new day resets `count` to 1.
    @discardableResult
    static func bump(key: String) -> Int {
        guard let defaults = UserDefaults(suiteName: appGroupSuiteName) else { return -1 }
        let today = utcDayString()
        var current = Record(utcDay: today, count: 0)
        if let data = defaults.data(forKey: key),
            let decoded = try? JSONDecoder().decode(Record.self, from: data),
            decoded.utcDay == today
        {
            current = decoded
        }
        current.count += 1
        if let data = try? JSONEncoder().encode(current) {
            defaults.set(data, forKey: key)
        }
        return current.count
    }

    static func utcDayString(_ date: Date = Date()) -> String {
        var c = Calendar(identifier: .gregorian)
        c.timeZone = TimeZone(identifier: "UTC") ?? .gmt
        let comps = c.dateComponents([.year, .month, .day], from: date)
        return String(
            format: "%04d-%02d-%02d",
            comps.year ?? 0, comps.month ?? 0, comps.day ?? 0
        )
    }
}
