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-token-${tokenCalls}`,
                    expires_in: 300
                })
            } as Response;
        }

        if (url.pathname.endsWith("/liveBroadcasts")) {
            liveBroadcastCalls += 1;
            const authHeader = init?.headers
                ? init.headers instanceof Headers
                    ? init.headers.get("Authorization")
                    : Array.isArray(init.headers)
                      ? (init.headers.find(([k]) => k.toLowerCase() === "authorization")?.[1] ?? null)
                      : (Object.entries(init.headers).find(([k]) => k.toLowerCase() === "authorization")?.[1] as
                            | string
                            | undefined) ?? null
                : null;
            if (!authHeader?.startsWith("Bearer oauth-token-")) {
                return {
                    ok: false,
                    status: 401,
                    statusText: "Unauthorized"
                } as Response;
            }
            return {
                ok: true,
                status: 200,
                statusText: "OK",
                json: async () => ({
                    items: [
                        {
                            snippet: {
                                liveChatId: "oauth-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: "oauth-youtube-msg-1",
                    snippet: { displayMessage: "hello from oauth youtube" },
                    authorDetails: { displayName: "yt-oauth-user" }
                },
                {
                    id: "oauth-youtube-msg-1",
                    snippet: { displayMessage: "duplicate oauth id" },
                    authorDetails: { displayName: "yt-oauth-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 {
        adapter.setAdminPresenceActive(true);
        adapter.armDiscovery();
        await delay(120);
        adapter.stop();
        await delay(20);

        assert(tokenCalls >= 1, "Expected oauth token call.");
        assert(liveBroadcastCalls >= 1, "Expected liveBroadcasts discovery call.");
        assert(streamCalls >= 1, "Expected live chat streaming call.");
        assert(seen.length === 1, "Expected one deduplicated oauth chat_ingest.");
        assert(seen[0].platform === "youtube", "Expected youtube platform.");
        assert(seen[0].author === "yt-oauth-user", "Expected author mapping.");
        assert(seen[0].message === "hello from oauth youtube", "Expected message mapping.");
        assert(
            logs.some((entry) => entry.message === "youtube_live_chat_discovered"),
            "Expected discovery log in oauth mode."
        );

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