import Foundation

/// Versioned metadata carried alongside a watch audio recording over
/// `WCSession.transferFile(_:metadata:)`. The watch encodes it into the
/// transfer's metadata dictionary; the phone decodes it on delivery.
///
/// Versioned so a newer watch build can extend the field set without an older
/// phone build silently misreading it: a missing, unknown, or newer version
/// decodes to `nil` (a forward gate). On that outcome the phone still stages the
/// audio bytes but skips ingest, so a future phone build can pick them up.
///
/// Lives in `Shared/`, compiled into the iOS app and the watch app (not the Mac
/// app). Foundation-only, so it is safe on both platforms.
struct AudioNotePayload: Equatable, Sendable {
    /// The wire version this build writes. Bump only when the field set changes
    /// in a way an older decoder can't interpret.
    static let currentVersion = 1

    /// ULID string minted on the watch at record start — the note's identity and
    /// its UTC time bucket. Also the staged filename base on the phone.
    let id: String
    /// Wall-clock instant recording started.
    let recordedAt: Date
    /// Recording length in seconds.
    let duration: TimeInterval
    /// IANA time-zone identifier the recording was made in (e.g. "Europe/Berlin"),
    /// or nil if unknown.
    let timeZoneID: String?

    private enum Key {
        static let version = "v"
        static let id = "id"
        static let recordedAt = "recordedAt"
        static let duration = "duration"
        static let timeZone = "tz"
    }

    init(id: String, recordedAt: Date, duration: TimeInterval, timeZoneID: String?) {
        self.id = id
        self.recordedAt = recordedAt
        self.duration = duration
        self.timeZoneID = timeZoneID
    }

    /// A plist-serializable dictionary for `WCSession.transferFile(_:metadata:)`.
    /// Every value type (Int, String, Date, Double) survives WatchConnectivity's
    /// metadata plist encoding.
    func metadata() -> [String: Any] {
        var dict: [String: Any] = [
            Key.version: Self.currentVersion,
            Key.id: id,
            Key.recordedAt: recordedAt,
            Key.duration: duration,
        ]
        if let timeZoneID { dict[Key.timeZone] = timeZoneID }
        return dict
    }

    /// Decode a received metadata dictionary. Returns `nil` when the version is
    /// missing, unknown, or newer than this build understands (the forward gate),
    /// or when a required field is absent or malformed.
    init?(metadata: [String: Any]) {
        guard let version = metadata[Key.version] as? Int,
              version >= 1, version <= Self.currentVersion,
              let id = metadata[Key.id] as? String,
              let recordedAt = metadata[Key.recordedAt] as? Date,
              let duration = metadata[Key.duration] as? Double else { return nil }
        self.id = id
        self.recordedAt = recordedAt
        self.duration = duration
        self.timeZoneID = metadata[Key.timeZone] as? String
    }
}

/// Phone → watch acknowledgment that a recording reached a terminal state on
/// the phone (durably ingested into the iCloud container, or permanently
/// vetoed). Sent over `transferUserInfo` — queued and durable, so an ack
/// survives both apps being closed. **Only** this ack lets the watch delete
/// its local copy of a recording; WatchConnectivity-level delivery success is
/// deliberately not trusted, because the phone can still fail after `didReceive`
/// returns (a staging or iCloud write failure would otherwise lose the audio
/// forever — the watch's copy is the last line of defense).
struct IngestAck: Equatable, Sendable {
    static let currentVersion = 1

    /// ULID string of the acknowledged recording.
    let id: String

    private enum Key {
        static let version = "ackV"
        static let id = "ackID"
    }

    init(id: String) {
        self.id = id
    }

    /// A plist-serializable dictionary for `WCSession.transferUserInfo(_:)`.
    func userInfo() -> [String: Any] {
        [Key.version: Self.currentVersion, Key.id: id]
    }

    /// Decode a received userInfo dictionary; nil when it isn't an ack this
    /// build understands (same forward-gate shape as `AudioNotePayload`).
    init?(userInfo: [String: Any]) {
        guard let version = userInfo[Key.version] as? Int,
              version >= 1, version <= Self.currentVersion,
              let id = userInfo[Key.id] as? String else { return nil }
        self.id = id
    }
}
