import { InMemoryEventBus } from "../hub/eventBus";
import { startYouTubeAdapter } from "../platform/youtube";

function delay(ms: number): Promise<void> {
    return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
}

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

async function main(): Promise<void> {
    const bus = new InMemoryEventBus();
    const seen: Array<{ platform: string; author: string; message: string }> = [];
    const logs: Array<{ message: string; fields: Record<string, unknown> }> = [];
    let tokenCalls = 0;
    let liveBroadcastCalls = 0;
    let streamCalls = 0;

    bus.on("chat_ingest", async (event) => {
        seen.push({
            platform: event.payload.platform,
            author: event.payload.author,
            message: event.payload.message
        });
    });

    const fakeFetch: typeof fetch = async (input, init) => {
        const url =
            typeof input === "string" ? new URL(input) : input instanceof URL ? input : new URL(input.url);

        if (url.hostname === "oauth2.googleapis.com" && url.pathname === "/token") {
            tokenCalls += 1;
            return {
                ok: true,
                status: 200,
                statusText: "OK",
                json: async () => ({
                    access_token: "oauth-phase18-token",
                    expires_in: 300
                })
            } as Response;
        }

        if (url.pathname.endsWith("/liveBroadcasts")) {
            liveBroadcastCalls += 1;
            return {
                ok: true,
                status: 200,
                statusText: "OK",
                json: async () => ({
                    items: [{ snippet: { liveChatId: "phase18-live-chat-id" } }]
                })
            } as Response;
        }

        throw new Error(`Unexpected URL in fakeFetch: ${url.toString()}`);
    };
    const fakeStreamList = async function* () {
        streamCalls += 1;
        yield {
            nextPageToken: "next",
            items: [
                {
                    id: "phase18-msg-1",
                    snippet: { displayMessage: "hello from phase18 youtube" },
                    authorDetails: { displayName: "yt-user" }
                }
            ]
        };
    };

    const adapter = startYouTubeAdapter({
        eventBus: bus,
        apiKey: "fake-key",
        oauthClientId: "client-id",
        oauthClientSecret: "client-secret",
        oauthRefreshToken: "refresh-token",
        pollMs: 10,
        discoveryPollMs: 10,
        errorLogCooldownMs: 2000,
        fetchImpl: fakeFetch,
        streamListImpl: fakeStreamList,
        log: (message, fields = {}) => {
            logs.push({ message, fields });
        }
    });

    try {
        await delay(40);
        assert(liveBroadcastCalls === 0, "Expected no discovery calls while discovery is paused.");
        assert(
            adapter.status().state === "paused",
            "Expected adapter to start with discovery paused."
        );

        adapter.setAdminPresenceActive(true);
        adapter.armDiscovery();
        await delay(70);

        assert(tokenCalls >= 1, "Expected oauth token acquisition.");
        assert(liveBroadcastCalls >= 1, "Expected discovery call after arming discovery.");
        assert(streamCalls >= 1, "Expected live chat streaming after discovery.");
        assert(seen.length >= 1, "Expected at least one chat message emission.");

        console.log(
            JSON.stringify(
                {
                    ok: true,
                    tokenCalls,
                    liveBroadcastCalls,
                    streamCalls,
                    emittedMessages: seen.length
                },
                null,
                2
            )
        );
    } finally {
        adapter.stop();
    }
}

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