import Foundation
import CoreData

// MARK: - App Group bridge for the Quick Update share extension
//
// The share extension can't open the CloudKit-backed Core Data store, so the app
// maintains a lightweight mirror of active sources in the App Group defaults and
// the extension appends "pending updates" to a queue there. The app ingests the
// queue on every activation, creating real snapshots.

/// Snapshot of an active source, enough for the extension's picker.
struct SharedSourceInfo: Codable, Identifiable {
    let id: UUID
    let name: String
    let latestValue: Double
    let currencyCode: String
    /// True when a value was already recorded this month (by app or extension).
    var updatedThisMonth: Bool
}

/// A value captured from the share extension, waiting to become a Snapshot.
struct PendingQuickUpdate: Codable {
    let sourceId: UUID
    let amount: Double
    let capturedAt: Date
}

enum SharedQuickUpdateStore {
    private static let mirrorKey = "sharedSourceMirror"
    private static let queueKey = "pendingQuickUpdates"

    static var defaults: UserDefaults? {
        UserDefaults(suiteName: AppConstants.appGroupIdentifier)
    }

    // MARK: Mirror (app writes, extension reads)

    static func writeMirror(_ sources: [SharedSourceInfo]) {
        guard let data = try? JSONEncoder().encode(sources) else { return }
        defaults?.set(data, forKey: mirrorKey)
    }

    static func readMirror() -> [SharedSourceInfo] {
        guard let data = defaults?.data(forKey: mirrorKey),
              let decoded = try? JSONDecoder().decode([SharedSourceInfo].self, from: data) else { return [] }
        return decoded
    }

    // MARK: Pending queue (extension writes, app drains)

    static func appendPending(_ update: PendingQuickUpdate) {
        var queue = readPending()
        queue.append(update)
        if let data = try? JSONEncoder().encode(queue) {
            defaults?.set(data, forKey: queueKey)
        }
        // Optimistically mark the source as updated in the mirror so the extension
        // suggests the next pending source on the following invocation.
        var mirror = readMirror()
        if let idx = mirror.firstIndex(where: { $0.id == update.sourceId }) {
            mirror[idx].updatedThisMonth = true
            writeMirror(mirror)
        }
    }

    static func readPending() -> [PendingQuickUpdate] {
        guard let data = defaults?.data(forKey: queueKey),
              let decoded = try? JSONDecoder().decode([PendingQuickUpdate].self, from: data) else { return [] }
        return decoded
    }

    static func clearPending() {
        defaults?.removeObject(forKey: queueKey)
    }
}

// MARK: - App-side sync & ingestion

enum SharedQuickUpdateSync {
    /// Refreshes the source mirror for the extension. Call on app activation and
    /// after snapshot saves.
    @MainActor
    static func refreshMirror() {
        let context = CoreDataStack.shared.viewContext
        let request = InvestmentSource.fetchRequest()
        request.predicate = NSPredicate(format: "isActive == YES")
        request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        guard let sources = try? context.fetch(request) else { return }

        let settings = AppSettings.getOrCreate(in: context)
        let calendar = Calendar.current
        let monthStart = calendar.date(from: calendar.dateComponents([.year, .month], from: Date())) ?? Date()

        let mirror = sources.map { source in
            SharedSourceInfo(
                id: source.id,
                name: source.name,
                latestValue: NSDecimalNumber(decimal: source.latestValue).doubleValue,
                currencyCode: source.account?.currency ?? settings.currency,
                updatedThisMonth: (source.latestSnapshot?.date ?? .distantPast) >= monthStart
            )
        }
        SharedQuickUpdateStore.writeMirror(mirror)
    }

    /// Drains the extension's pending queue into real snapshots. Returns how many
    /// snapshots were created. Call on app activation.
    @MainActor
    @discardableResult
    static func ingestPending() -> Int {
        let pending = SharedQuickUpdateStore.readPending()
        guard !pending.isEmpty else { return 0 }

        let context = CoreDataStack.shared.viewContext
        let request = InvestmentSource.fetchRequest()
        guard let sources = try? context.fetch(request) else { return 0 }
        let byId = Dictionary(uniqueKeysWithValues: sources.map { ($0.id, $0) })

        var created = 0
        for update in pending {
            guard let source = byId[update.sourceId] else { continue }
            let snapshot = Snapshot(context: context)
            snapshot.id = UUID()
            snapshot.value = NSDecimalNumber(value: update.amount)
            snapshot.date = update.capturedAt
            snapshot.source = source
            created += 1
        }

        if context.hasChanges {
            do {
                try context.save()
            } catch {
                print("Failed to ingest pending quick updates: \(error)")
                return 0
            }
        }
        SharedQuickUpdateStore.clearPending()
        refreshMirror()
        return created
    }
}
