// bobcord_swift.swift — SDK BobCord (REST + builders)
// User + Bot + EmbedBuilder + ActionRow / Button / WebAction
// API: https://aml-s9xx-box.taildd440a.ts.net/api/v1.1

import Foundation

let bobcordDefaultBase = "https://aml-s9xx-box.taildd440a.ts.net/api/v1.1"

func webActionConfirm(_ title: String = "Confirmer", _ body: String = "", then: [String: Any]? = nil) -> [String: Any] {
    var o: [String: Any] = ["type": "confirm", "title": title, "body": body]
    if let then { o["then"] = then }
    return o
}
func webActionSendMessage(_ content: String, channel: String? = nil, serverId: Int? = nil, confirm: [String: Any]? = nil) -> [String: Any] {
    var o: [String: Any] = ["type": "send_message", "content": content]
    if let channel { o["channel"] = channel }
    if let serverId { o["server_id"] = serverId }
    if let confirm { o["confirm"] = confirm }
    return o
}
func webActionReact(_ emoji: String = "👍", messageId: Any = "self", confirm: [String: Any]? = nil) -> [String: Any] {
    var o: [String: Any] = ["type": "react", "emoji": emoji, "message_id": messageId]
    if let confirm { o["confirm"] = confirm }
    return o
}
func button(_ label: String, style: String = "SECONDARY", customId: String? = nil, url: String? = nil, webAction: [String: Any]? = nil, disabled: Bool = false) -> [String: Any] {
    let st = style.uppercased()
    var o: [String: Any] = ["type": "BUTTON", "style": st, "label": label, "disabled": disabled]
    if st == "LINK" {
        guard let url else { fatalError("LINK requires url") }
        o["url"] = url
    } else {
        guard let customId else { fatalError("BUTTON requires custom_id") }
        o["custom_id"] = customId
    }
    if st == "WEB_ACTION" {
        guard let webAction else { fatalError("WEB_ACTION requires web_action") }
        o["web_action"] = webAction
    }
    return o
}
func actionRow(_ components: [[String: Any]]) -> [String: Any] {
    ["type": "ACTION_ROW", "components": Array(components.prefix(5))]
}
func actionRows(_ rows: [[String: Any]]) -> [[String: Any]] { Array(rows.prefix(4)) }

public class EmbedBuilder {
    private var data: [String: Any] = ["fields": [[String: Any]]()]
    @discardableResult public func title(_ t: String) -> EmbedBuilder { data["title"] = t; return self }
    @discardableResult public func description(_ d: String) -> EmbedBuilder { data["description"] = d; return self }
    @discardableResult public func color(_ c: Int) -> EmbedBuilder { data["color"] = c & 0xFFFFFF; return self }
    @discardableResult public func addField(_ name: String, _ value: String, inline: Bool = false) -> EmbedBuilder {
        var fields = data["fields"] as! [[String: Any]]
        fields.append(["name": name, "value": value, "inline": inline])
        data["fields"] = fields
        return self
    }
    @discardableResult public func footer(_ text: String) -> EmbedBuilder { data["footer"] = ["text": text]; return self }
    public func build() -> [String: Any] { data }
}

public class User {
    public let token: String
    public var baseUrl: String
    public var me: [String: Any]?
    public init(_ token: String, baseUrl: String = bobcordDefaultBase) {
        self.token = token.trimmingCharacters(in: .whitespacesAndNewlines)
        self.baseUrl = baseUrl
    }
    public func request(_ method: String, _ path: String, body: [String: Any]? = nil, completion: @escaping (Result<[String: Any]?, Error>) -> Void) {
        let url = URL(string: "\(baseUrl.trimmingCharacters(in: CharacterSet(charactersIn: "/")))/\(path.trimmingCharacters(in: CharacterSet(charactersIn: "/")))")!
        var req = URLRequest(url: url)
        req.httpMethod = method
        req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        if let body { req.httpBody = try? JSONSerialization.data(withJSONObject: body) }
        URLSession.shared.dataTask(with: req) { data, res, err in
            if let err { completion(.failure(err)); return }
            let code = (res as? HTTPURLResponse)?.statusCode ?? 0
            if code == 204 { completion(.success(nil)); return }
            let obj = (try? JSONSerialization.jsonObject(with: data ?? Data())) as? [String: Any]
            if code >= 400 { completion(.failure(NSError(domain: "BobCord", code: code, userInfo: obj))); return }
            completion(.success(obj))
        }.resume()
    }
    public func send(_ content: String, channel: String = "général", serverId: Int = 1, embeds: [[String: Any]]? = nil, actionRows: [[String: Any]]? = nil, completion: @escaping (Result<[String: Any]?, Error>) -> Void) {
        var body: [String: Any] = ["content": content, "channel": channel, "server_id": serverId]
        if let embeds { body["embeds"] = embeds }
        if let actionRows { body["action_rows"] = actionRows }
        request("POST", "/message", body: body, completion: completion)
    }
}

public class Bot: User {}
