// EarnedStats for apps on iPhone, iPad, Mac, Apple TV, Apple Watch and Vision Pro.
//
//   EarnedStats.configure(siteId: "SITE_ID")
//   EarnedStats.screen("Home")
//   EarnedStats.track("signup", ["plan": "pro"])
//
// Screens are sent as app://<bundle id>/<screen>. One random install id, made on first launch and kept only in the app,
// makes one install one visitor. No advertising id, no device identifier, nothing to ask permission for.

import Foundation
#if canImport(UIKit)
import UIKit
#endif
#if canImport(WatchKit)
import WatchKit
#endif
#if canImport(AppKit)
import AppKit
#endif
#if canImport(SwiftUI)
import SwiftUI
#endif

public enum EarnedStats {
    public static let sdkVersion = "1.0.0"

    /// Start tracking. Call once, as early as possible (App init or application(_:didFinishLaunchingWithOptions:)).
    /// - Parameters:
    ///   - siteId: the site id from EarnedStats, Settings, Tracking code.
    ///   - host: where events are sent; your own domain if you proxy it.
    ///   - appId: defaults to the bundle id. Must match the app id the site was added with (or one in its settings).
    ///   - debug: print events instead of sending them.
    public static func configure(siteId: String, host: String = "https://earnedstats.com", appId: String? = nil, debug: Bool = false) {
        Tracker.shared.configure(siteId: siteId, host: host, appId: appId ?? Bundle.main.bundleIdentifier ?? "app.unknown", debug: debug)
    }

    /// A screen view. `name` becomes the page path: "Home" is /Home, "settings/billing" is /settings/billing.
    public static func screen(_ name: String, _ params: [String: String] = [:]) {
        Tracker.shared.screen(name, params)
    }

    /// A goal or custom event, with up to 10 properties.
    public static func track(_ name: String, _ properties: [String: Any] = [:]) {
        Tracker.shared.enqueue(type: "goal", path: Tracker.shared.lastScreen, extra: ["n": String(name.prefix(64)), "p": properties.isEmpty ? nil : properties])
    }

    /// Tie this install to your own user, so their visits and payments show on one profile.
    public static func identify(userId: String, email: String? = nil, name: String? = nil) {
        var p: [String: Any] = ["user_id": userId]
        if let email { p["email"] = email }
        if let name { p["name"] = name }
        Tracker.shared.enqueue(type: "identify", path: Tracker.shared.lastScreen, extra: ["p": p])
    }

    /// Pass a deep link or universal link the app was opened with: its utm_ and ref parameters credit the next screen
    /// view to that campaign.
    public static func open(url: URL) {
        Tracker.shared.campaign(from: url)
    }

    /// This install's visitor id, known after the first event is sent. Give it to your payment provider as
    /// es_visitor_id (for RevenueCat: Purchases.shared.attribution.setAttributes(["es_visitor_id": id])).
    public static var visitorId: String? { Tracker.shared.visitorId }

    /// Called with the visitor id as soon as it is known (at once if it already is).
    public static func onVisitorId(_ block: @escaping (String) -> Void) { Tracker.shared.onVisitorId(block) }

    /// Stop or resume sending (for an in-app analytics opt out). Kept across launches.
    public static var enabled: Bool {
        get { !UserDefaults.standard.bool(forKey: "es_disabled") }
        set { UserDefaults.standard.set(!newValue, forKey: "es_disabled"); if !newValue { Tracker.shared.clearQueue() } }
    }

    /// Send what is queued now (it is also sent on its own every few seconds and when the app goes to the background).
    public static func flush() { Tracker.shared.flush() }
}

#if canImport(SwiftUI)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public extension View {
    /// Sends a screen view each time this view appears.
    func trackScreen(_ name: String, _ params: [String: String] = [:]) -> some View {
        onAppear { EarnedStats.screen(name, params) }
    }
}
#endif

final class Tracker {
    static let shared = Tracker()

    private let queueLock = DispatchQueue(label: "com.earnedstats.queue")
    private var siteId = ""
    private var endpoint: URL?
    private var appId = ""
    private var debug = false
    private var queue: [[String: Any]] = []
    private var sending = false
    private var timer: Timer?
    private var foregroundSince: Date?
    private var pendingCampaign: [URLQueryItem] = []
    private var visitorBlocks: [(String) -> Void] = []
    private(set) var lastScreen = "/"
    // Read on the main thread once (UIKit), then used from any thread.
    private var isPad = false
    private var width: Int?
    private let maxQueue = 500
    private let maxAge: TimeInterval = 48 * 3600

    var visitorId: String? { UserDefaults.standard.string(forKey: "es_visitor") }

    private lazy var installId: String = {
        if let id = UserDefaults.standard.string(forKey: "es_install") { return id }
        let id = UUID().uuidString.lowercased()
        UserDefaults.standard.set(id, forKey: "es_install")
        return id
    }()

    private var queueFile: URL? {
        let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
        return dir?.appendingPathComponent("earnedstats-queue.json")
    }

    func configure(siteId: String, host: String, appId: String, debug: Bool) {
        queueLock.sync {
            self.siteId = siteId
            self.appId = appId.lowercased()
            self.debug = debug
            var h = host
            while h.hasSuffix("/") { h.removeLast() }
            self.endpoint = URL(string: h + "/api/event")
            self.loadQueue()
        }
        let start = {
            #if os(iOS)
            self.isPad = UIDevice.current.userInterfaceIdiom == .pad
            #endif
            #if os(iOS) || os(tvOS)
            self.width = Int(UIScreen.main.bounds.width)
            #endif
            self.observeLifecycle()
            self.foregroundSince = Date()
            self.timer?.invalidate()
            self.timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { _ in Tracker.shared.flush() }
            self.flush()
        }
        if Thread.isMainThread { start() } else { DispatchQueue.main.async(execute: start) }
    }

    func screen(_ name: String, _ params: [String: String]) {
        let clean = name.trimmingCharacters(in: CharacterSet(charactersIn: "/ ")).replacingOccurrences(of: " ", with: "-")
        var path = "/" + clean
        var items = params.map { URLQueryItem(name: $0.key, value: $0.value) }
        queueLock.sync {
            items += pendingCampaign
            pendingCampaign = []
        }
        if !items.isEmpty {
            var c = URLComponents()
            c.queryItems = items
            path += "?" + (c.percentEncodedQuery ?? "")
        }
        lastScreen = "/" + clean
        enqueue(type: "pageview", path: path, extra: [:])
    }

    func campaign(from url: URL) {
        let keys: Set<String> = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "ref", "via"]
        let items = (URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []).filter { keys.contains($0.name) }
        queueLock.sync { pendingCampaign = items }
    }

    func enqueue(type: String, path: String, extra: [String: Any?]) {
        guard EarnedStats.enabled else { return }
        var e: [String: Any] = ["t": type, "path": path, "ts": Date().timeIntervalSince1970]
        for (k, v) in extra { if let v { e[k] = v } }
        let count: Int = queueLock.sync {
            queue.append(e)
            if queue.count > maxQueue { queue.removeFirst(queue.count - maxQueue) }
            saveQueue()
            return queue.count
        }
        if type != "pageview" || count >= 20 { flush() } else { flushSoon() }
    }

    private func flushSoon() {
        DispatchQueue.global().asyncAfter(deadline: .now() + 1) { self.flush() }
    }

    func clearQueue() { queueLock.sync { queue = []; saveQueue() } }

    func onVisitorId(_ block: @escaping (String) -> Void) {
        if let v = visitorId { block(v) } else { queueLock.sync { visitorBlocks.append(block) } }
    }

    /// Sends queued events one by one, oldest first. Events that fail on the network stay queued for the next try.
    func flush() {
        let next: [String: Any]? = queueLock.sync {
            guard !sending, endpoint != nil, !siteId.isEmpty, let first = queue.first else { return nil }
            sending = true
            return first
        }
        guard let event = next, let endpoint else { return }
        let age = Date().timeIntervalSince1970 - (event["ts"] as? Double ?? 0)
        if age > maxAge { finish(drop: true); return flush() }

        var body: [String: Any] = [
            "w": siteId,
            "t": event["t"] as? String ?? "pageview",
            "u": "app://\(appId)\(event["path"] as? String ?? "/")",
            "m": meta(),
        ]
        if age > 2 { body["ago"] = Int(age * 1000) }
        for k in ["n", "p", "d", "r"] { if let v = event[k] { body[k] = v } }
        if let sw = width { body["sw"] = sw }

        if debug {
            print("EarnedStats (debug, not sent):", body)
            finish(drop: true)
            return flush()
        }
        guard JSONSerialization.isValidJSONObject(body), let data = try? JSONSerialization.data(withJSONObject: body) else {
            finish(drop: true)
            return flush()
        }
        var req = URLRequest(url: endpoint, timeoutInterval: 15)
        req.httpMethod = "POST"
        req.httpBody = data
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        req.setValue("EarnedStats-Swift/\(EarnedStats.sdkVersion)", forHTTPHeaderField: "User-Agent")
        URLSession.shared.dataTask(with: req) { [weak self] data, response, error in
            guard let self else { return }
            let status = (response as? HTTPURLResponse)?.statusCode ?? 0
            if error != nil || status == 0 || status >= 500 {
                self.finish(drop: false) // offline or a server hiccup: keep it for later
                return
            }
            if let data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let v = json["v"] as? String {
                self.storeVisitor(v)
            }
            self.finish(drop: true) // sent, or refused for good (4xx): never retried
            self.flush()
        }.resume()
    }

    private func finish(drop: Bool) {
        queueLock.sync {
            if drop, !queue.isEmpty { queue.removeFirst(); saveQueue() }
            sending = false
        }
    }

    private func storeVisitor(_ v: String) {
        guard v != visitorId else { return }
        UserDefaults.standard.set(v, forKey: "es_visitor")
        let blocks: [(String) -> Void] = queueLock.sync { let b = visitorBlocks; visitorBlocks = []; return b }
        DispatchQueue.main.async { blocks.forEach { $0(v) } }
    }

    private func meta() -> [String: Any] {
        let info = Bundle.main.infoDictionary
        var m: [String: Any] = ["i": installId, "sdk": "swift/\(EarnedStats.sdkVersion)"]
        if let v = info?["CFBundleShortVersionString"] as? String { m["av"] = v }
        let os = ProcessInfo.processInfo.operatingSystemVersion
        m["osv"] = "\(os.majorVersion).\(os.minorVersion)"
        #if os(iOS)
        let pad = isPad
        m["os"] = pad ? "ipados" : "ios"
        m["dev"] = pad ? "tablet" : "mobile"
        #elseif os(macOS)
        m["os"] = "macos"; m["dev"] = "desktop"
        #elseif os(tvOS)
        m["os"] = "tvos"; m["dev"] = "tv"
        #elseif os(watchOS)
        m["os"] = "watchos"; m["dev"] = "mobile"
        #elseif os(visionOS)
        m["os"] = "visionos"; m["dev"] = "desktop"
        #endif
        return m
    }

    // Foreground time is sent as a ping when the app goes to the background, so visit length counts only real use.
    private func observeLifecycle() {
        let nc = NotificationCenter.default
        #if os(iOS) || os(tvOS) || os(visionOS)
        nc.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in self?.backgrounded() }
        nc.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] _ in self?.foregroundSince = Date() }
        #elseif os(macOS)
        nc.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.backgrounded() }
        nc.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.foregroundSince = Date() }
        #endif
    }

    private func backgrounded() {
        if let since = foregroundSince {
            let ms = Int(Date().timeIntervalSince(since) * 1000)
            if ms >= 1000 { enqueue(type: "ping", path: lastScreen, extra: ["d": min(ms, 600_000)]) }
        }
        foregroundSince = nil
        #if os(iOS) || os(tvOS) || os(visionOS)
        var task: UIBackgroundTaskIdentifier = .invalid
        task = UIApplication.shared.beginBackgroundTask { UIApplication.shared.endBackgroundTask(task) }
        flush()
        DispatchQueue.global().asyncAfter(deadline: .now() + 5) { UIApplication.shared.endBackgroundTask(task) }
        #else
        flush()
        #endif
    }

    private func loadQueue() {
        guard let file = queueFile, let data = try? Data(contentsOf: file),
              let arr = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return }
        queue = arr
    }

    private func saveQueue() {
        guard let file = queueFile else { return }
        try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
        if let data = try? JSONSerialization.data(withJSONObject: queue) { try? data.write(to: file, options: .atomic) }
    }
}
