//
//  Venbit.swift
//  Venbit App Tracking
//
//  One file. Drop it into your project, call Venbit.start once at launch, and
//  your campaigns start reporting installs.
//
//      Venbit.start(appKey: "vba_your_key")
//
//  WHAT IT SENDS, AND WHAT IT DELIBERATELY DOES NOT.
//
//  Sent, once, on the first launch after an install: a random id this file
//  generated itself, your app's own bundle id, your device model, and your
//  iOS version. The bundle id is what lets Venbit work out which App Store
//  listing is yours, so nobody has to type it in.
//
//  Sent, at most once per day after that: the same random id, your app's
//  version and the iOS version — "this install opened today". That single
//  daily note is what powers active users, retention and version adoption
//  on the dashboard, as counted facts rather than estimates.
//
//  Purchases report themselves. StoreKit already tells your app about every
//  purchase, renewal and refund, so this listens rather than making you write
//  the same call at every till. Only what your own app sells, only after this
//  install existed, each one counted once. Pass watchPurchases: false to send
//  your own instead.
//
//  Not sent, ever: the advertising identifier, the vendor identifier, your
//  name, your email, your contacts, your location, your other apps. Nothing
//  that identifies you as a person and nothing that follows you into anybody
//  else's app.
//
//  So there is no App Tracking Transparency prompt to show, because by
//  Apple's own definition this is not tracking: nothing here is joined to
//  data from another company's app or website. It is one app counting where
//  its own installs came from.
//
//  The random id lives in the keychain rather than UserDefaults, for one
//  practical reason: it survives a delete and reinstall, so a person who
//  removes the app and puts it back is recognised as the same install instead
//  of being counted twice.
//

import Foundation
import Security
import StoreKit

public enum Venbit {

    // MARK: - Public

    nonisolated private static let foregroundObserver: Void = {
        NotificationCenter.default.addObserver(
            forName: Notification.Name("UIApplicationDidBecomeActiveNotification"),
            object: nil,
            queue: nil
        ) { _ in state.pulseIfDue() }
    }()

    /// What produced this install, once we know.
    public struct Attribution: Sendable {
        /// The campaign name from the link that was tapped, if we matched one.
        nonisolated public let campaign: String?
        /// "high", "likely" or "none". Never a guess dressed as a fact.
        /// ("exact" is reserved for a future deterministic join and is not
        /// produced today.)
        nonisolated public let confidence: String
        /// Where inside your app the tapped link meant to land, if it said.
        nonisolated public let deepLink: String?
    }

    /// Call once, as early in launch as you like.
    ///
    /// Safe to call on every launch: after the first one it returns without
    /// touching the network. Nothing here blocks; the completion arrives on
    /// the main queue.
    nonisolated public static func start(
        appKey: String,
        endpoint: String = "https://venbit.com",
        /* Purchases report themselves. StoreKit already tells the app about
           every purchase, renewal and refund it makes, so asking a developer
           to also call event("purchase") by hand is asking them to write code
           that duplicates something the system is already saying out loud,
           and to remember it at every till in their app. Off is available for
           anybody who would rather send their own. */
        watchPurchases: Bool = true,
        onAttribution: (@Sendable (Attribution) -> Void)? = nil
    ) {
        state.configure(appKey: appKey, endpoint: endpoint)
        state.claimIfNeeded(onAttribution: onAttribution)
        state.pulseIfDue()
        /* An app that lives in the background for days never relaunches, so
           coming back to the foreground is the other moment a day begins.
           The raw notification name keeps this file UIKit-free, and the
           static once-token means an app calling start() from both its
           AppDelegate and SceneDelegate still registers exactly one
           observer. */
        _ = Self.foregroundObserver
        if watchPurchases, #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
            Purchases.watch(state)
        }
    }

    /// Something happened that is worth money, or is on the way to it.
    ///
    /// Called whenever you like, as often as you like. The campaign report is
    /// only as useful as what you send here: installs tell you which campaign
    /// is busy, and this tells you which one pays.
    ///
    ///     Venbit.event("trial_started")
    ///     Venbit.event("purchase", valueCents: 4999, currency: "USD")
    nonisolated public static func event(
        _ kind: String,
        valueCents: Int? = nil,
        currency: String? = nil,
        meta: [String: String]? = nil
    ) {
        state.send(kind: kind, valueCents: valueCents, currency: currency, meta: meta)
    }

    /// The install id, if you want to line our numbers up with your own.
    nonisolated public static var installId: String { state.installId }

    /// Forget everything and behave like a brand new install next launch.
    ///
    /// FOR TESTING, AND YOU WILL NEED IT. The install id and the "already
    /// claimed" marker live in the keychain so that deleting and reinstalling
    /// your app is recognised as the same person rather than counted twice.
    /// The side effect is that once you have tested your integration, you
    /// cannot test it again: the second run sees the marker and correctly does
    /// nothing. Deleting the app does not help, because that is the whole
    /// point of the keychain.
    ///
    /// Call this, relaunch, and the next launch claims afresh. Never ship it
    /// on a path a real user can reach: to them it means being counted twice.
    nonisolated public static func resetForTesting() {
        state.forgetEverything()
    }

    // MARK: - Guts

    nonisolated private static let state = Store()

    private final class Store: @unchecked Sendable {
        nonisolated private let lock = NSLock()
        nonisolated(unsafe) private var appKey = ""
        nonisolated(unsafe) private var endpoint = "https://venbit.com"

        /// Generated here, kept in the keychain, never derived from anything
        /// about the device or the person holding it. Behind the lock,
        /// because purchase watching asks from background Tasks while the
        /// claim asks from the main thread, and a lazy var's first run is
        /// not atomic: two racing reads once minted two different ids, so
        /// the claim and a purchase could name different installs.
        nonisolated(unsafe) private var cachedInstallId: String?

        nonisolated var installId: String {
            lock.lock()
            defer { lock.unlock() }
            if let cached = cachedInstallId { return cached }
            if let existing = Keychain.read(Self.idKey) {
                cachedInstallId = existing
                return existing
            }
            let fresh = UUID().uuidString
            Keychain.write(Self.idKey, value: fresh)
            cachedInstallId = fresh
            return fresh
        }

        nonisolated private static let idKey = "com.venbit.attribution.install"
        nonisolated private static let claimedKey = "com.venbit.attribution.claimed"
        /* The key, kept. event() used to do nothing at all if start() had not
           run yet in this process: no error, no warning, just a conversion
           that never arrived. A purchase reported from a background launch
           was the case that would have hit it. */
        nonisolated private static let appKeyStore = "com.venbit.attribution.appKey"
        /// When this install first existed, so a purchase made before it can
        /// be told apart from one it caused.
        nonisolated private static let bornKey = "com.venbit.attribution.born"

        /// The moment this install id was minted, as seconds since 1970.
        /// Locked for the same reason installId is: read-then-write races.
        nonisolated var bornAt: Double {
            lock.lock()
            defer { lock.unlock() }
            if let raw = Keychain.read(Self.bornKey), let n = Double(raw) { return n }
            let now = Date().timeIntervalSince1970
            Keychain.write(Self.bornKey, value: String(now))
            return now
        }

        /// Clears every trace of this install. See Venbit.resetForTesting.
        nonisolated func forgetEverything() {
            for key in [Self.idKey, Self.claimedKey, Self.bornKey, Self.appKeyStore, "com.venbit.attribution.txns"] {
                Keychain.remove(key)
            }
            lock.lock()
            cachedInstallId = nil
            lock.unlock()
            UserDefaults.standard.removeObject(forKey: Self.pulsedKey)
        }

        nonisolated func configure(appKey: String, endpoint: String) {
            /* STAMPED BEFORE THE LOCK IS TAKEN, and it has to stay that way.
               bornAt takes this same lock, NSLock is not recursive, and a
               second acquire on one thread blocks it forever. Reading it
               inside the critical section below therefore hung whichever
               thread called start() — which our own instructions put on the
               main thread at launch, so the app froze before it drew
               anything and iOS killed it with the launch watchdog.

               Kept as an ordering rule rather than swapped for an
               NSRecursiveLock: a recursive lock would have silently
               absorbed this and every future re-entrancy like it, and this
               file's whole job is to be boring inside somebody else's app. */
            _ = bornAt // stamped on the first run, not on the first purchase
            lock.lock()
            defer { lock.unlock() }
            self.appKey = appKey
            self.endpoint = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
            Keychain.write(Self.appKeyStore, value: appKey)
        }

        nonisolated func claimIfNeeded(onAttribution: (@Sendable (Attribution) -> Void)?) {
            lock.lock()
            let key = appKey
            let base = endpoint
            lock.unlock()
            guard !key.isEmpty else { return }

            /* The marker is written only after the server ANSWERS. It used
               to be written before the request, which made every failed
               first-launch claim permanent: airplane mode on first open
               meant this install never existed, its campaign credit and
               every future purchase orphaned to organic forever. The server
               is idempotent on (app, install), so the retry a later launch
               sends can never create a second row; an in-flight flag keeps
               one launch from claiming twice concurrently. */
            if Keychain.read(Self.claimedKey) != nil { return }
            lock.lock()
            if claimInFlight {
                lock.unlock()
                return
            }
            claimInFlight = true
            lock.unlock()

            var body: [String: Any] = [
                "appKey": key,
                "installId": installId,
                "deviceModel": Self.model(),
                "osVersion": Self.osVersion(),
                /* The app saying which app it is. This is what removes the
                   "go and find your numeric App Store id" step from setup
                   entirely: Apple publishes a free lookup from a bundle id to
                   a store id, so the app tells us where it lives rather than
                   somebody typing it. Nothing about a person. */
                "bundleId": Bundle.main.bundleIdentifier ?? "",
                "platform": "ios",
            ]
            /* A TestFlight build or an App Review launch is not a customer.
               Said out loud so it can be excluded rather than quietly
               inflating somebody's campaign. */
            if Self.isSandbox() { body["sandbox"] = true }

            post("\(base)/api/attribution/claim", body: body) { [weak self] json in
                if let self {
                    self.lock.lock()
                    self.claimInFlight = false
                    self.lock.unlock()
                }
                guard let json else { return }
                Keychain.write(Self.claimedKey, value: "1")
                let result = Attribution(
                    campaign: json["campaign"] as? String,
                    confidence: json["confidence"] as? String ?? "none",
                    deepLink: json["deepLink"] as? String
                )
                DispatchQueue.main.async { onAttribution?(result) }
            }
        }

        /* "This install opened today", at most once per UTC day. The day
           marker is written only after the server answers, so a launch with
           no signal simply tries again next time — a missed pulse is a
           missing row, and rows are what the dashboard counts. */
        nonisolated private static let pulsedKey = "com.venbit.attribution.pulsed"
        nonisolated(unsafe) private var pulseInFlight = false
        nonisolated(unsafe) private var claimInFlight = false

        nonisolated func pulseIfDue() {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "yyyy-MM-dd"
            formatter.timeZone = TimeZone(identifier: "UTC")
            let today = formatter.string(from: Date())

            /* One request at a time: launch and the app's first activation
               arrive in the same breath, and without this every first open
               of the day was two pulses — half a customer's rate budget
               spent on duplicates the table would just merge anyway. The
               check and the take happen inside ONE lock section: split
               across two, both callers passed the check before either set
               the flag, which is the double-pulse this guard exists for. */
            lock.lock()
            var key = appKey
            let base = endpoint
            if pulseInFlight || UserDefaults.standard.string(forKey: Self.pulsedKey) == today {
                lock.unlock()
                return
            }
            pulseInFlight = true
            lock.unlock()

            if key.isEmpty { key = Keychain.read(Self.appKeyStore) ?? "" }
            guard !key.isEmpty else {
                lock.lock()
                pulseInFlight = false
                lock.unlock()
                return
            }

            var body: [String: Any] = [
                "appKey": key,
                "installId": installId,
                "appVersion": (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "",
                "osVersion": Self.osVersion(),
            ]
            if Self.isSandbox() { body["sandbox"] = true }

            post("\(base)/api/attribution/pulse", body: body) { [weak self] json in
                if let self {
                    self.lock.lock()
                    self.pulseInFlight = false
                    self.lock.unlock()
                }
                guard json != nil else { return }
                UserDefaults.standard.set(today, forKey: Self.pulsedKey)
            }
        }

        nonisolated func send(
            kind: String,
            valueCents: Int? = nil,
            currency: String? = nil,
            meta: [String: String]? = nil,
            onDelivered: (@Sendable () -> Void)? = nil,
            onFailed: (@Sendable () -> Void)? = nil
        ) {
            lock.lock()
            var key = appKey
            let base = endpoint
            lock.unlock()
            /* Fall back to the stored key rather than dropping the event.
               start() runs at launch and events come later, so in practice
               these are the same; the exception is a background launch, and
               a silently discarded purchase is the worst possible thing for
               this file to do. */
            if key.isEmpty { key = Keychain.read(Self.appKeyStore) ?? "" }
            guard !key.isEmpty else { return }

            var body: [String: Any] = ["appKey": key, "installId": installId, "kind": kind]
            /* The event's own id: the server dedupes on it, so a retry, a
               proxy replay, or a re-walked entitlement can never count the
               same money twice. */
            body["eventId"] = UUID().uuidString
            if let valueCents { body["valueCents"] = valueCents }
            if let currency { body["currency"] = currency }
            if let meta { body["meta"] = meta }
            /* Test builds say so on the event itself: a sandbox purchase
               whose install claim was lost used to land as real revenue. */
            if Self.isSandbox() { body["sandbox"] = true }
            post("\(base)/api/attribution/event", body: body) { json in
                if json != nil { onDelivered?() } else { onFailed?() }
            }
        }

        /* Fire and forget, with a short timeout. Nothing this file does is
           worth making somebody's app feel slow, and an install that fails to
           report is a missing row, not a broken app. */
        nonisolated private func post(
            _ urlString: String,
            body: [String: Any],
            completion: (@Sendable ([String: Any]?) -> Void)?
        ) {
            guard let url = URL(string: urlString),
                  let data = try? JSONSerialization.data(withJSONObject: body)
            else { return }
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpBody = data
            request.timeoutInterval = 10
            URLSession.shared.dataTask(with: request) { data, response, _ in
                guard let completion else { return }
                /* Only a 2xx counts as answered. Error replies carry JSON
                   bodies too, and treating them as success once marked a
                   rate-limited day as pulsed — permanently undercounting a
                   customer's biggest day. */
                let status = (response as? HTTPURLResponse)?.statusCode ?? 0
                guard (200..<300).contains(status) else {
                    completion(nil)
                    return
                }
                let json = data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]
                completion(json)
            }.resume()
        }

        /* "iPhone16,2" and so on. The marketing name is not available without
           shipping a lookup table that goes stale every September. */
        nonisolated private static func model() -> String {
            var info = utsname()
            uname(&info)
            /* Read as bytes up to the first null rather than through any of
               the C-string initialisers: every one of those is either
               deprecated or too new to rely on, and this file has to compile
               without a warning on whatever SDK the customer happens to be
               building against. */
            let raw = withUnsafeBytes(of: &info.machine) { buffer -> String in
                String(decoding: buffer.prefix(while: { $0 != 0 }), as: UTF8.self)
            }
            #if targetEnvironment(simulator)
            return ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? raw
            #else
            return raw.isEmpty ? "Unknown" : raw
            #endif
        }

        nonisolated private static func osVersion() -> String {
            let v = ProcessInfo.processInfo.operatingSystemVersion
            return "\(v.majorVersion).\(v.minorVersion)"
        }

        /* TestFlight and App Review are not customers who found you in an ad,
           and counting them as such makes a review cycle look like a campaign.
           TestFlight ships a receipt named sandboxReceipt; the App Store used
           to ship one named receipt.

           USED TO. Since the StoreKit 2 era the store no longer writes the
           legacy receipt file at install, so a fresh App Store download has
           NEITHER file, and the first version of this check read that absence
           as "not from the App Store". Every real customer's install arrived
           flagged sandbox, the dashboard filters sandbox out of the numbers,
           and a launched app looked like nobody had come. A missing receipt
           means nothing anymore; the marks that still mean something are the
           sandbox receipt (TestFlight and App Review write it) and an
           embedded provisioning profile (dev, ad-hoc and enterprise builds
           carry one inside the bundle; store-signed builds never do).

           Found by looking in the container rather than through
           Bundle.appStoreReceiptURL, which is deprecated on current SDKs.
           Apple's replacement is StoreKit's AppTransaction, which is async and
           wants the network, and this has to answer during launch without
           waiting for anything. An SDK that adds a warning to somebody else's
           build log is an SDK they take back out. */
        nonisolated private static func isSandbox() -> Bool {
            #if DEBUG
            return true
            #elseif targetEnvironment(simulator)
            return true
            #else
            if let library = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first {
                let storeKit = library.deletingLastPathComponent().appendingPathComponent("StoreKit")
                if FileManager.default.fileExists(atPath: storeKit.appendingPathComponent("sandboxReceipt").path) {
                    return true
                }
            }
            if Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") != nil {
                return true
            }
            /* Store-signed, no sandbox receipt, no embedded profile: a
               customer. This is the default on purpose. Wrongly counting a
               stray ad-hoc build is a rounding error; wrongly hiding every
               real install is a dead dashboard. */
            return false
            #endif
        }
    }

    // MARK: - Purchases, reported by StoreKit rather than by hand

    /* WHY THIS EXISTS.
     *
     * The campaign list is only worth reading if it knows what each campaign
     * earned, and until now that meant every customer writing event("purchase")
     * at every place their app takes money, and keeping it right forever. Most
     * never will, and the ones who do will miss the renewal path.
     *
     * StoreKit already announces all of it. Listening costs nothing, applies
     * to any app that drops this file in, and reports the real price in the
     * real currency rather than whatever a hand-written call remembered to
     * pass.
     *
     * THREE THINGS IT IS CAREFUL ABOUT, because the naive version overstates
     * revenue badly:
     *
     *  - A purchase made BEFORE this install existed is not this install's.
     *    Restores and transactions carried over from another device arrive
     *    through the same door, and crediting them to the campaign that
     *    produced this install would hand a campaign money it never earned.
     *  - The same transaction must not be counted twice, across launches or
     *    across a reinstall. Each one is remembered by its id.
     *  - A refund is real news. StoreKit is the only place that knows, so a
     *    revoked transaction is reported rather than left standing as revenue
     *    that quietly stopped being revenue.
     */
    @available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
    private enum Purchases {
        nonisolated private static let seenKey = "com.venbit.attribution.txns"
        nonisolated private static let lock = NSLock()
        /* Ids claimed in THIS run, delivered or still in flight. The keychain
           check alone left two gaps that both happened in production (T&F,
           2026-08-16): Transaction.updates and currentEntitlements can hand
           over the same transaction within milliseconds, both passing the
           keychain check before either delivery lands (one renewal recorded
           three times in a tenth of a second); and a delivery whose reply is
           lost is never remembered, so the next launch reports it again. */
        nonisolated(unsafe) private static var claimed = Set<String>()

        nonisolated static func watch(_ store: Store) {
            Task.detached(priority: .background) {
                /* Anything already sitting unfinished, then everything that
                   happens from now on. Transaction.updates is the only path
                   that sees a renewal, which is the money a subscription app
                   actually lives on. */
                for await result in StoreKit.Transaction.updates {
                    guard case .verified(let txn) = result else { continue }
                    report(txn, to: store)
                }
            }
            Task.detached(priority: .background) {
                for await result in StoreKit.Transaction.currentEntitlements {
                    guard case .verified(let txn) = result else { continue }
                    report(txn, to: store)
                }
            }
        }

        /// Currencies that carry no minor unit (JPY, KRW, …) and the two
        /// that carry three. Multiplying a yen price by 100 used to report
        /// a ¥1,000 subscription as a thousand dollars.
        nonisolated private static let zeroDecimal: Set<String> = ["JPY", "KRW", "VND", "CLP", "ISK", "HUF", "TWD", "UGX", "RWF", "PYG", "KMF", "GNF", "DJF", "BIF", "VUV", "XAF", "XOF", "XPF"]
        nonisolated private static let threeDecimal: Set<String> = ["BHD", "KWD", "OMR", "JOD", "TND", "IQD", "LYD"]

        nonisolated private static func minorUnits(_ price: Decimal, currency: String?) -> Int {
            let code = (currency ?? "USD").uppercased()
            let factor: Decimal = zeroDecimal.contains(code) ? 1 : threeDecimal.contains(code) ? 1000 : 100
            return Int(NSDecimalNumber(decimal: price * factor).doubleValue.rounded())
        }

        nonisolated private static func report(_ txn: StoreKit.Transaction, to store: Store) {
            /* Family Sharing: this user paid nothing, a relative did.
               Counting the shared entitlement as this install's campaign
               revenue books money the install never earned. */
            guard txn.ownershipType == .purchased else { return }

            /* Older than the install itself. A restore, or a subscription
               bought on another device months ago: real money, but not money
               this campaign produced. A five-minute tolerance keeps the
               genuine onboarding purchase made moments before start() ran,
               while still excluding month-old restores. */
            guard txn.purchaseDate.timeIntervalSince1970 >= store.bornAt - 300 else { return }

            let refunded = txn.revocationDate != nil
            let id = "\(txn.id)\(refunded ? "-r" : "")"

            var cents: Int? = nil
            var currency: String? = nil
            if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
                currency = txn.currency?.identifier
            } else {
                /* iOS 15's only spelling. Without it, minorUnits assumed USD
                   and a ¥3,000 renewal became three hundred thousand cents. */
                currency = txn.currencyCode
            }
            if let price = txn.price {
                cents = minorUnits(price, currency: currency)
            }

            /* A refund for money that was never counted up must not be
               counted down. A transaction FIRST seen already revoked (the
               renewal fired while the app was closed, the refund landed
               before the next launch) has no positive side on our books, so
               sending its negative would subtract phantom revenue. Same for
               a revoked $0 trial: nothing to reverse. Both ids are put to
               bed so neither leg ever reports. */
            if refunded && (!wasDelivered(String(txn.id)) || (cents ?? 0) == 0) {
                lock.lock()
                claimed.insert(id)
                claimed.insert(String(txn.id))
                lock.unlock()
                remember(id)
                remember(String(txn.id))
                return
            }

            guard claim(id) else { return }

            /* The subscription's first PAID transaction is a purchase, even
               though StoreKit gives it originalID != id when a free trial
               came first: the conversion charge is the sub's second
               transaction. Booking it "renewal" made every trial-first app
               read as trials converting into nothing. The paid marker (one
               per subscription, kept with the delivered ids) says whether
               this subscription has ever paid before. A $0 transaction is
               the trial itself; a nil price is NOT free, it is a paid
               transaction whose price we could not read. */
            let isFree = cents == 0 && !refunded
            let paidBefore = wasDelivered("p-\(txn.originalID)")
            let kind = refunded ? "refund" : isFree ? "trial_started" : (paidBefore ? "renewal" : "purchase")

            store.send(
                kind: kind,
                /* A refund is money going the other way, said as a negative so
                   a campaign's total can come back down instead of standing at
                   a figure that stopped being true. */
                valueCents: refunded ? cents.map { -$0 } : cents,
                currency: currency,
                /* The StoreKit transaction id rides along so the SERVER can
                   refuse a replay it has already recorded. The device-side
                   memory above is best effort; this is the authority. */
                meta: ["product": txn.productID, "txn": String(txn.id)],
                /* Remembered only after the server answers: marking first
                   meant a purchase reported into a dead network was skipped
                   on every future launch — the lost report was permanent,
                   and it hit exactly the flaky-network purchases. */
                onDelivered: {
                    remember(id)
                    if !refunded && !isFree { remember("p-\(txn.originalID)") }
                },
                /* A failed send releases the claim, so a later re-emission
                   of the same transaction (this run or the next) can try
                   again instead of the money being lost to one bad radio
                   moment. */
                onFailed: { unclaim(id) }
            )
        }

        /// True when this id is ours to report: not delivered on an earlier
        /// launch, and not already claimed by a concurrent report this run.
        /// Claiming and checking happen under one lock, so two streams
        /// handing over the same transaction race for one slot.
        nonisolated private static func claim(_ id: String) -> Bool {
            lock.lock()
            defer { lock.unlock() }
            if claimed.contains(id) { return false }
            let seen = (Keychain.read(seenKey) ?? "").split(separator: ",").map(String.init)
            if seen.contains(id) { return false }
            claimed.insert(id)
            return true
        }

        nonisolated private static func unclaim(_ id: String) {
            lock.lock()
            defer { lock.unlock() }
            claimed.remove(id)
        }

        /// Whether this id ever reached the server (this run or an earlier
        /// launch). Distinct from claim(): asking does not take the slot.
        nonisolated private static func wasDelivered(_ id: String) -> Bool {
            lock.lock()
            defer { lock.unlock() }
            let seen = (Keychain.read(seenKey) ?? "").split(separator: ",").map(String.init)
            return seen.contains(id)
        }

        /// Records a delivered id. Kept small: the last few hundred are
        /// enough to stop a repeat, and an unbounded list in the keychain
        /// is its own problem. The server's own event dedupe is the
        /// backstop if an old id is ever evicted.
        nonisolated private static func remember(_ id: String) {
            lock.lock()
            defer { lock.unlock() }
            var seen = (Keychain.read(seenKey) ?? "").split(separator: ",").map(String.init)
            guard !seen.contains(id) else { return }
            seen.append(id)
            if seen.count > 300 { seen.removeFirst(seen.count - 300) }
            Keychain.write(seenKey, value: seen.joined(separator: ","))
        }
    }

    // MARK: - Keychain

    /* Why the keychain and not UserDefaults: UserDefaults is wiped when the
       app is deleted, so a reinstall would look like a brand new person and be
       counted, and matched, all over again. The keychain survives, which makes
       the claim safely repeatable. */
    private enum Keychain {
        nonisolated private static let service = "com.venbit.attribution"

        nonisolated static func read(_ account: String) -> String? {
            let query: [String: Any] = [
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrService as String: service,
                kSecAttrAccount as String: account,
                kSecReturnData as String: true,
                kSecMatchLimit as String: kSecMatchLimitOne,
            ]
            var out: CFTypeRef?
            guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess,
                  let data = out as? Data
            else { return nil }
            return String(data: data, encoding: .utf8)
        }

        nonisolated static func remove(_ account: String) {
            SecItemDelete([
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrService as String: service,
                kSecAttrAccount as String: account,
            ] as CFDictionary)
        }

        nonisolated static func write(_ account: String, value: String) {
            let base: [String: Any] = [
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrService as String: service,
                kSecAttrAccount as String: account,
            ]
            SecItemDelete(base as CFDictionary)
            var item = base
            item[kSecValueData as String] = Data(value.utf8)
            /* AfterFirstUnlock, not WhenUnlocked. An app can be launched by a
               push or a background refresh while the phone is still locked,
               and a WhenUnlocked item cannot be read then: the id would come
               back nil and a second install would be invented. */
            item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
            SecItemAdd(item as CFDictionary, nil)
        }
    }
}
