import { InMemoryEventBus } from "../hub/eventBus";
import { attachChatCommandParser } from "../hub/chatCommandParser";
import { createEvent } from "../hub/events";

function assert(condition: boolean, message: string): void {
    if (!condition) {
        throw new Error(message);
    }
}

async function main(): Promise<void> {
    const bus = new InMemoryEventBus();
    const parsed: Array<{ streamId: string; command: string; args: string[] }> = [];

    bus.on("chat_command", async (event) => {
        parsed.push({
            streamId: event.payload.streamId,
            command: event.payload.command,
            args: event.payload.args
        });
    });

    const detach = attachChatCommandParser(bus, () => {});

    await bus.emit(
        createEvent("chat_message", {
            streamId: "stream-1",
            platform: "test",
            author: "alice",
            message: "hello there"
        })
    );
    await bus.emit(
        createEvent("chat_message", {
            streamId: "stream-1",
            platform: "test",
            author: "alice",
            message: "!Poll start now"
        })
    );
    await bus.emit(
        createEvent("chat_message", {
            streamId: "stream-2",
            platform: "test",
            author: "bob",
            message: "   !status all good"
        })
    );
    await bus.emit(
        createEvent("chat_message", {
            streamId: "stream-2",
            platform: "test",
            author: "bob",
            message: "!"
        })
    );

    detach();

    assert(parsed.length === 2, "Expected exactly two parsed chat commands.");
    assert(parsed[0].streamId === "stream-1", "Expected first command stream id to match.");
    assert(parsed[0].command === "poll", "Expected command normalization to lowercase.");
    assert(parsed[0].args.join(" ") === "start now", "Expected command args to parse.");
    assert(parsed[1].streamId === "stream-2", "Expected second command stream id to match.");
    assert(parsed[1].command === "status", "Expected second command to parse.");
    assert(parsed[1].args.join(" ") === "all good", "Expected second command args to parse.");

    console.log(
        JSON.stringify(
            {
                ok: true,
                parsed
            },
            null,
            2
        )
    );
}

main().catch((error: unknown) => {
    const message = error instanceof Error ? error.message : String(error);
    console.error(message);
    process.exit(1);
});
