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();
    let tokenCalls = 0;
    let liveBroadcastCalls = 0;
    let streamCalls = 0;

    const fakeFetch: typeof fetch = async (input) => {
        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: "phase22-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: "phase22-ended-chat-id" } }]
                })
            } as Response;
        }

        throw new Error(`Unexpected URL in fakeFetch: ${url.toString()}`);
    };

    const fakeStreamList = async function* () {
        streamCalls += 1;
        yield {
            offlineAt: new Date().toISOString(),
            items: []
        };
    };

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

    try {
        adapter.armDiscovery();
        await delay(1500);

        const status = adapter.status();
        assert(tokenCalls >= 1, "Expected token acquisition.");
        assert(liveBroadcastCalls === 1, `Expected no immediate rediscovery loop; got ${liveBroadcastCalls}.`);
        assert(streamCalls === 1, `Expected no immediate restream loop; got ${streamCalls}.`);
        assert(status.state === "recovering", `Expected recovering state, got ${status.state}.`);

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

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