import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
#if canImport(UIKit)
import UIKit
#endif
#if canImport(AdServices)
import AdServices
#endif
#if canImport(Darwin)
import Darwin
#endif

/// Small, explicit mobile subscription telemetry. Keys must be public sub_pk_ keys.
public enum Submetry {
    private static let lock = NSLock()
    private static var client: Client?
    public static var onError: ((String) -> Void)?
    public static func configure(appId: String, key: String, userId: String? = nil, endpoint: URL = URL(string: "https://api.submetry.com/v1/events")!, environment: String? = nil, appleAdsAttribution: Bool = true) {
        guard !appId.isEmpty, appId.count<=128, key.hasPrefix("sub_pk_"), userId == nil || (userId!.count>0 && userId!.count<=128), environment == nil || ["production","debug","sandbox","testflight"].contains(environment!), endpoint.scheme == "https" || endpoint.host == "localhost" || endpoint.host == "127.0.0.1" else { report("Invalid project, public key, identity, environment or endpoint"); return }
        let directory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory
        let safeId = appId.unicodeScalars.map { CharacterSet.alphanumerics.contains($0) ? String($0) : "_" }.joined()
        lock.lock(); client?.stop(); client = nil
        let c = Client(appId: appId, key: key, endpoint: endpoint, userId: userId, environment: environment ?? detectedEnvironment(), file: directory.appendingPathComponent("Submetry/\(safeId)/queue.json"), appleAdsAttribution: appleAdsAttribution)
        client = c; lock.unlock()
    }
    static func report(_ message: String) { let callback=onError; DispatchQueue.global(qos:.utility).async { callback?(message) } }
    public static func configure(appId: String, apiKey: String, userId: String? = nil, endpoint: URL = URL(string: "https://api.submetry.com/v1/events")!, environment: String? = nil, appleAdsAttribution: Bool = true) {
        configure(appId: appId, key: apiKey, userId: userId, endpoint: endpoint, environment: environment, appleAdsAttribution: appleAdsAttribution)
    }
    public static func track(_ name: String, properties: [String: Any] = [:]) { current()?.track(name, properties: properties) }
    public static func identify(_ userId: String) { current()?.identify(userId) }
    public static func flush() { current()?.flush(force: true) }
    public static func onboardingStep(_ index: Int, id: String, answer: String? = nil) { var p: [String: Any] = ["index": index, "id": id]; if let answer { p["answer"] = answer }; track("onboarding_step", properties: p) }
    public static func onboardingCompleted() { track("onboarding_completed") }
    public static func paywallShown(_ id: String) { current()?.setPaywall(id); track("paywall_shown", properties: ["paywall": id]) }
    public static func paywallPlanSelected(_ plan: String) { track("paywall_plan_selected", properties: ["plan": plan]) }
    public static func paywallDismissed() { track("paywall_dismissed"); current()?.setPaywall(nil) }
    public static func trialStarted(_ plan: String) { track("trial_started", properties: ["plan": plan]); current()?.flush() }
    public static func purchaseCompleted(_ plan: String) { track("purchase_completed", properties: ["plan": plan]); current()?.flush() }
    private static func current() -> Client? { lock.lock(); defer { lock.unlock() }; return client }
    private static func detectedEnvironment() -> String {
        #if DEBUG
        return "debug"
        #else
        // A sandbox receipt alone cannot distinguish TestFlight from an App Store sandbox.
        // Pass environment:"testflight" explicitly when the distribution is known.
        if Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" { return "sandbox" }
        return "production"
        #endif
    }
}

enum JSONValue: Codable {
    case string(String), number(Double), bool(Bool), null, array([JSONValue]), object([String: JSONValue])
    init(from decoder: Decoder) throws {
        let c = try decoder.singleValueContainer()
        if c.decodeNil() { self = .null }
        else if let v = try? c.decode(Bool.self) { self = .bool(v) }
        else if let v = try? c.decode(Double.self) { self = .number(v) }
        else if let v = try? c.decode(String.self) { self = .string(v) }
        else if let v = try? c.decode([JSONValue].self) { self = .array(v) }
        else { self = .object(try c.decode([String: JSONValue].self)) }
    }
    func encode(to encoder: Encoder) throws {
        var c = encoder.singleValueContainer()
        switch self { case .string(let v): try c.encode(v); case .number(let v): try c.encode(v); case .bool(let v): try c.encode(v); case .null: try c.encodeNil(); case .array(let v): try c.encode(v); case .object(let v): try c.encode(v) }
    }
}
struct Event: Codable { let id: String; let ts: Double; let name: String; let sid: String; let aid: String; let uid: String?; let props: [String: JSONValue]; let context: [String: String] }
struct Batch: Codable { let app_id: String; let events: [Event] }
struct QueueState: Codable { var anonymousId: String; var userId: String?; var firstOpenRecorded: Bool; var events: [Event]; var attributionRecorded: Bool? = nil }

final class Client {
    typealias Transport = (URLRequest, @escaping (Result<Int, Error>) -> Void) -> Void
    private let lock = NSLock(), appId: String, key: String, endpoint: URL, file: URL, environment: String, transport: Transport
    private var state: QueueState, sessionId = "sess_"+UUID().uuidString, paywall: String?, inFlight = false, stopped = false, failures = 0
    private var nextAttempt = Date.distantPast
    private var timer: DispatchSourceTimer?, retry: DispatchWorkItem?, observers: [NSObjectProtocol] = []
    var snapshot: QueueState { lock.lock(); defer {lock.unlock()}; return state }
    init(appId: String, key: String, endpoint: URL, userId: String?, environment: String, file: URL, flushInterval: TimeInterval = 10, transport: @escaping Transport = Client.send, appleAdsAttribution: Bool = true, attributionProvider: @escaping () throws -> String? = Client.attributionToken) {
        self.appId=appId; self.key=key; self.endpoint=endpoint; self.environment=environment; self.file=file; self.transport=transport
        state = QueueState(anonymousId:"anon_"+UUID().uuidString, userId:nil, firstOpenRecorded:false, events:[])
        if let data=try? Data(contentsOf:file) {
            do {state=try JSONDecoder().decode(QueueState.self,from:data)}
            catch {do {try data.write(to:file.appendingPathExtension("corrupted.json"),options:.atomic);Submetry.report("Corrupted queue archived before starting a new installation identity")}
                catch {stopped=true;Submetry.report("Cannot archive corrupted queue; telemetry paused to preserve original data")}}
        }
        guard !stopped else{return}
        if let userId {state.userId=userId}
        let first = !state.firstOpenRecorded; state.firstOpenRecorded=true
        if first {track("first_open",properties:[:])};track("session_start",properties:[:]);track("app_open",properties:[:])
        if flushInterval > 0 {
            let t=DispatchSource.makeTimerSource(queue:DispatchQueue(label:"com.submetry.flush"));t.schedule(deadline:.now()+flushInterval,repeating:flushInterval);t.setEventHandler{[weak self] in self?.flush()};t.resume();timer=t
        }
        if appleAdsAttribution && state.attributionRecorded != true {
            DispatchQueue.global(qos:.utility).async { [weak self] in self?.requestAttribution(attributionProvider, attempt:0) }
        }
        #if canImport(UIKit)
        observers.append(NotificationCenter.default.addObserver(forName:UIApplication.didEnterBackgroundNotification,object:nil,queue:.main){[weak self] _ in self?.flush()})
        observers.append(NotificationCenter.default.addObserver(forName:UIApplication.willEnterForegroundNotification,object:nil,queue:.main){[weak self] _ in self?.startSession()})
        #endif
    }
    static func attributionToken() throws -> String? {
        #if canImport(AdServices) && os(iOS)
        if #available(iOS 14.3, *) { return try AAAttribution.attributionToken() }
        #endif
        return nil
    }
    private func requestAttribution(_ provider: @escaping () throws -> String?, attempt: Int) {
        lock.lock();let allowed = !stopped && state.attributionRecorded != true;lock.unlock();guard allowed else{return}
        do {
            guard let token=try provider(),!token.isEmpty,token.count<=16384 else{return}
            lock.lock();guard !stopped,state.attributionRecorded != true else{lock.unlock();return};state.attributionRecorded=true;lock.unlock()
            track("install_attribution",properties:["token":token]);flush()
        } catch {
            if attempt<2 {DispatchQueue.global(qos:.utility).asyncAfter(deadline:.now()+5){[weak self] in self?.requestAttribution(provider,attempt:attempt+1)}}
            else {Submetry.report("Apple Ads attribution token unavailable; no attribution recorded")}
        }
    }
    deinit {stop()}
    func stop() { lock.lock(); stopped=true;timer?.cancel();timer=nil;retry?.cancel();retry=nil;lock.unlock();for observer in observers {NotificationCenter.default.removeObserver(observer)};observers=[] }
    func startSession() {lock.lock();guard !stopped else{lock.unlock();return};sessionId="sess_"+UUID().uuidString;lock.unlock();track("session_start",properties:[:]);track("app_open",properties:[:])}
    func setPaywall(_ id: String?) {lock.lock();guard !stopped else{lock.unlock();return};paywall=id;lock.unlock()}
    func identify(_ id: String) {guard !id.isEmpty,id.count<=128 else{return};lock.lock();guard !stopped else{lock.unlock();return};state.userId=id;persist();lock.unlock();track("identity_linked",properties:[:])}
    func track(_ name: String, properties: [String: Any]) {
        guard name.range(of:"^[a-z][a-z0-9_]{0,79}$",options:.regularExpression) != nil,!name.hasPrefix("rc_"),JSONSerialization.isValidJSONObject(properties),let json=try? JSONSerialization.data(withJSONObject:properties),json.count<=8192,let props=try? JSONDecoder().decode([String:JSONValue].self,from:json) else {Submetry.report("Invalid event name/properties");return}
        lock.lock();guard !stopped else {lock.unlock();return};var enriched=props;if let paywall, enriched["paywall"]==nil {enriched["paywall"] = .string(paywall)}
        guard let encoded=try? JSONEncoder().encode(enriched),encoded.count<=8192 else{lock.unlock();Submetry.report("Enriched properties exceed 8 KB");return}
        state.events.append(Event(id:"evt_"+UUID().uuidString,ts:Date().timeIntervalSince1970,name:name,sid:sessionId,aid:state.anonymousId,uid:state.userId,props:enriched,context:context()));persist();let full=state.events.count>=20;lock.unlock();if full {flush()}
    }
    func flush(force: Bool = false) {
        lock.lock();guard !stopped,!inFlight,!state.events.isEmpty,(force || Date()>=nextAttempt) else{lock.unlock();return}
        let batch=Array(state.events.prefix(20));guard let payload=try? JSONEncoder().encode(Batch(app_id:appId,events:batch)) else{lock.unlock();return}
        inFlight=true;retry?.cancel();retry=nil;lock.unlock()
        var request=URLRequest(url:endpoint);request.httpMethod="POST";request.timeoutInterval=20;request.httpBody=payload;request.setValue("application/json",forHTTPHeaderField:"Content-Type");request.setValue("Bearer \(key)",forHTTPHeaderField:"Authorization")
        transport(request){[weak self] result in
            guard let self else{return};self.lock.lock();self.inFlight=false;guard !self.stopped else{self.lock.unlock();return}
            let status:Int;if case .success(let code)=result {status=code}else{status=0}
            let success=(200..<300).contains(status)
            let permanent=[400,413,422].contains(status)
            let archived = permanent && self.archiveRejected(batch)
            if success || archived {let ids=Set(batch.map{$0.id});self.state.events.removeAll{ids.contains($0.id)};self.failures=0;self.nextAttempt = .distantPast;self.persist()}
            else {self.failures+=1}
            let more = !self.state.events.isEmpty && !self.stopped
            let delay=min(300.0,pow(2.0,Double(min(self.failures,8))))
            if !success,!archived,more {self.nextAttempt=Date().addingTimeInterval(delay);let retry=DispatchWorkItem{[weak self] in self?.flush()};self.retry=retry;DispatchQueue.global(qos:.utility).asyncAfter(deadline:.now()+delay,execute:retry)}
            self.lock.unlock()
            if (success || archived),more {self.flush()}
            if archived {Submetry.report("Rejected batch archived to queue.json.rejected.json; inspect validation errors before replay")}
            else if !success {Submetry.report("Event upload failed; batch retained for retry")}

        }
    }
    private func archiveRejected(_ batch:[Event]) -> Bool {
        let archive=file.appendingPathExtension("rejected.json")
        do {let previous=(try? JSONDecoder().decode([Event].self,from:Data(contentsOf:archive))) ?? [];try JSONEncoder().encode(previous+batch).write(to:archive,options:.atomic);return true}
        catch {Submetry.report("Cannot archive rejected batch; original queue retained");return false}
    }
    private func persist() {
        do {try FileManager.default.createDirectory(at:file.deletingLastPathComponent(),withIntermediateDirectories:true);let data=try JSONEncoder().encode(state);try data.write(to:file,options:.atomic)}catch {Submetry.report("Unable to persist telemetry queue: \(error.localizedDescription)")}
    }
    private func context() -> [String:String] {
        ["device_model":Self.deviceModel(),"platform":"ios","app_version":Bundle.main.object(forInfoDictionaryKey:"CFBundleShortVersionString") as? String ?? "unknown","build":Bundle.main.object(forInfoDictionaryKey:"CFBundleVersion") as? String ?? "unknown","os_version":ProcessInfo.processInfo.operatingSystemVersionString,"locale":Locale.current.identifier,"timezone":TimeZone.current.identifier,"environment":environment]
    }
    private static func deviceModel() -> String {
        #if canImport(Darwin)
        var system=utsname();uname(&system);let capacity=MemoryLayout.size(ofValue:system.machine)
        return withUnsafePointer(to:&system.machine) { pointer in pointer.withMemoryRebound(to:CChar.self,capacity:capacity) { String(cString:$0) } }
        #else
        return "unknown"
        #endif
    }
    static func send(_ request: URLRequest, completion: @escaping (Result<Int,Error>) -> Void) {
        URLSession.shared.dataTask(with:request){_,response,error in if let error {completion(.failure(error))}else if let response=response as? HTTPURLResponse {completion(.success(response.statusCode))}else{completion(.success(0))}}.resume()
    }
}
