/**
 * Build a ChatGateway from `~/.opensquid/config.json`'s
 * `chat_connections` block. Skips adapters whose tokens are missing —
 * opensquid works with zero, one, or all three chat platforms wired.
 *
 * Per-platform adapter modules (telegram/discord/slack) are imported
 * dynamically here so the factory doesn't pull all three SDK trees
 * into the cold-start path. Each adapter's own dynamic-import of its
 * SDK runs only inside `.start()`.
 */
import { ChatGateway, ChatGatewayError } from "./gateway.js";
import { loadChatConfig, validateChatConfig } from "./config.js";
export async function buildChatGateway(opts = {}) {
    const config = opts.config ?? (await loadChatConfig(opts.dataRoot));
    const issues = validateChatConfig(config);
    const adapters = [];
    const activated = [];
    // Each block: only activate if (a) config block exists AND (b) no
    // validation issue against this platform's tokens. An issue here
    // means the user has a partial config (e.g. typo'd token) — better
    // to skip with a logged warning than throw and prevent the other
    // adapters from working.
    if (config.telegram && !issues.some((i) => i.platform === "telegram")) {
        const { TelegramAdapter } = await import("./adapters/telegram.js");
        adapters.push(new TelegramAdapter(config.telegram));
        activated.push("telegram");
    }
    if (config.discord && !issues.some((i) => i.platform === "discord")) {
        const { DiscordAdapter } = await import("./adapters/discord.js");
        adapters.push(new DiscordAdapter(config.discord));
        activated.push("discord");
    }
    if (config.slack && !issues.some((i) => i.platform === "slack")) {
        const { SlackAdapter } = await import("./adapters/slack.js");
        adapters.push(new SlackAdapter(config.slack));
        activated.push("slack");
    }
    // Throw when the user clearly mis-configured a token. All three
    // platforms are now implemented (v0.7c), so any validation issue
    // against a configured platform is a real problem.
    const blockingIssues = issues.filter((i) => (i.platform === "telegram" && !!config.telegram) ||
        (i.platform === "discord" && !!config.discord) ||
        (i.platform === "slack" && !!config.slack));
    if (blockingIssues.length > 0 && adapters.length === 0) {
        throw new ChatGatewayError("chat connections configured but failed validation — see issues", `validation: ${blockingIssues
            .map((i) => `${i.platform}.${i.field}: ${i.problem}`)
            .join("; ")}`);
    }
    return { gateway: new ChatGateway(adapters), activated, issues };
}
