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") }

        try await bot.connect()

        await withThrowingTaskGroup(of: Void.self) { group in
            for i in 0...5 {
                group.addTask {
                    for await event in await bot.events {
                        print(i)
                        switch event {
                            case .messageCreate(let event):
                                try await MessageHandler(ctx: event, client: bot.client).handle()
                            default:
                                continue
                        }
                    }
                }
            }

        }
        print("bottom of main")
    }
}
