import Foundation
import DiscordKit
import SwiftDotenv

@main
struct Zundamon {
    nonisolated(unsafe) static private(set) var ownID: String? = nil

    static func main() async throws {
        if case .failure = Result(catching: { try Dotenv.configure() }) {
            print("Failed to load .env file")
        }

        let token = ProcessInfo.processInfo.environment["DISCORD_TOKEN"]!

        guard !token.isEmpty else { fatalError("Err: Empty DISCORD_TOKEN. Exiting...") }

        let intents: Intents = [.guilds, .guildMessages, .messageContent, .guildMembers, .directMessages]

        let bot = try await DiscordKit.Bot(token: token, intents: intents)
        ownID = try await bot.client.getOwnUser().id
        guard ownID != nil else { fatalError("Failed to get own User ID") }

        await withThrowingTaskGroup(of: Void.self) { taskGroup in
            taskGroup.addTask {
                try await bot.connect()
            }

            taskGroup.addTask {
                for await event in await bot.events {
                    dump(event)
                    switch event.d {
                        case .messageCreate(let event):
                            try await MessageHandler(ctx: event, client: bot.client).handle()
                        default:
                            continue
                    }
                }
            }
        }
    }
}

//struct EventHandler: GatewayEventHandler {
//    let event: Gateway.Event
//    let client: any DiscordClient
//
//    func onMessageCreate(_ payload: Gateway.MessageCreate) async throws {
//        try await MessageHandler(ctx: payload, client: client).handle()
//    }
//
//}
