//
//  GenerateImageAI.swift
//  WoWonder
//
//  Created by iMac on 03/06/25.
//  Copyright © 2025 ScriptSun. All rights reserved.
//

import Foundation
import UIKit
import Alamofire

struct Text2ImageModel : Codable {
    
    let id : String?
    let backend_request_id : String?
    let output_url : String?
    let share_url : String?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case backend_request_id = "backend_request_id"
        case output_url = "output_url"
        case share_url = "share_url"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decodeIfPresent(String.self, forKey: .id)
        backend_request_id = try values.decodeIfPresent(String.self, forKey: .backend_request_id)
        output_url = try values.decodeIfPresent(String.self, forKey: .output_url)
        share_url = try values.decodeIfPresent(String.self, forKey: .share_url)
    }

}

class GenerateImageAi {
    
    private static let artUrl = "https://api.deepai.org/api/text2img"
    private static let keyDeepAi = "57469926-b75d-439b-a284-52d7ec4cf944"
    
    private var usageCount: Int = 0
    private var lastUsageTimestamp: TimeInterval = 0
    private var currentTime: TimeInterval {
        return Date().timeIntervalSince1970 * 1000 // Current time in milliseconds
    }
    
    private let keyUsageCount = "GenerateAi_usageCount"
    private let keyLastUsageTimestamp = "GenerateAi_lastUsageTimestamp"
    private let maxUsageLimit = 3
    private let timeLimitMillis: TimeInterval = 24 * 60 * 60 * 1000
    
    private static var instance: GenerateImageAi?
    
    static var shared: GenerateImageAi {
        if instance == nil {
            instance = GenerateImageAi()
        }
        return instance!
    }
    
    private init() {
        // Load usage count and last usage timestamp from UserDefaults
        let defaults = UserDefaults.standard
        usageCount = defaults.integer(forKey: keyUsageCount)
        lastUsageTimestamp = defaults.double(forKey: keyLastUsageTimestamp)
    }
    
    func checkGenerateImageAi() -> Bool {
        let isPro = AppInstance.instance.userProfile?.is_pro ?? "0"
        
        let timeSinceLastUsage = currentTime - lastUsageTimestamp
        if timeSinceLastUsage >= timeLimitMillis {
            usageCount = 0
        }
        
        if usageCount >= maxUsageLimit && isPro == "0" {
            return false
        }
        return true
    }
    
    func generateImage(text: String, completion: @escaping (_ Success: Text2ImageModel?) -> Void) {
        guard checkGenerateImageAi() else {
            completion(nil)
            return
        }
        
        let params = [
            "text": text
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = GenerateImageAi.artUrl
        print("urlString >>>>> ", urlString)
        let headers: HTTPHeaders = [
            "Content-Type": "application/x-www-form-urlencoded",
            "api-key": GenerateImageAi.keyDeepAi
        ]
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { response in
            if let res = response.value as? [String: Any] {
                print("response >>>>> ", res)
                do {
                    let data = try JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try JSONDecoder().decode(Text2ImageModel.self, from: data)
                    self.usageCount += 1
                    self.lastUsageTimestamp = self.currentTime
                    
                    // Save updated values to UserDefaults
                    let defaults = UserDefaults.standard
                    defaults.set(self.usageCount, forKey: self.keyUsageCount)
                    defaults.set(self.lastUsageTimestamp, forKey: self.keyLastUsageTimestamp)
                    completion(result)
                } catch {
                    print("Error: ", error.localizedDescription)
                    completion(nil)
                }
            } else {
                print("Error: \(response.error?.localizedDescription ?? "Unknown error")")
                completion(nil)
            }
        }
    }
    
}
