/**
 * weekly-digest command — generates and delivers a weekly evaluation digest.
 *
 * Queries the Sanity Content Lake for reports within the configured
 * lookback window, computes trend analysis, and delivers the digest
 * via Slack or stdout.
 *
 */
import { Command } from "commander";
export function createWeeklyDigestCommand() {
    return new Command("digest")
        .description("Generate and deliver a weekly evaluation digest")
        .option("-n, --dry-run", "Print to stdout only, do not send to Slack", false)
        .option("--lookback <days>", "Lookback window in days (default: from config or 7)", parseInt)
        .option("-f, --format <fmt>", "Output format: console or json", "console")
        .action(async (opts) => {
        const { generateDigest } = await import("../schedules/digest.js");
        const { getDigestConfig } = await import("../schedules/loader.js");
        const { buildSlackMessage } = await import("@sanity/ailf-core");
        const { resolveDashboardBaseUrl } = await import("../sinks/slack/dashboard-links.js");
        const dashboardBaseUrl = resolveDashboardBaseUrl();
        console.log();
        console.log("=== AI Literacy Weekly Digest ===");
        console.log();
        // Load digest config
        const digestConfig = getDigestConfig();
        const lookbackDays = opts.lookback ?? digestConfig?.lookbackDays ?? 7;
        console.log(`  Lookback: ${lookbackDays} days`);
        console.log(`  Mode: ${opts.dryRun ? "dry run (stdout only)" : "live"}`);
        console.log();
        // Generate digest — uses AILF_REPORT_* env vars for report store access
        const digest = await generateDigest({
            dataset: process.env.AILF_REPORT_DATASET,
            lookbackDays,
            projectId: process.env.AILF_REPORT_PROJECT_ID,
            token: process.env.AILF_REPORT_SANITY_API_TOKEN ??
                process.env.SANITY_API_TOKEN,
        });
        if (!digest) {
            console.log("  No reports found in the lookback window. Nothing to send.");
            process.exit(0);
        }
        // Output summary
        console.log(`  Reports found: ${digest.reportCount}`);
        console.log(`  Overall: ${Math.round(digest.overallLatest)} (${digest.overallTrend})`);
        console.log(`  Improved: ${digest.improved.join(", ") || "none"}`);
        console.log(`  Regressed: ${digest.regressed.join(", ") || "none"}`);
        console.log(`  Stable: ${digest.stable.join(", ") || "none"}`);
        console.log();
        if (opts.format === "json") {
            console.log(JSON.stringify(digest, null, 2));
            return;
        }
        // Format for Slack
        const message = buildSlackMessage({ kind: "digest", digest, cadence: "weekly" }, { dashboardBaseUrl });
        if (opts.dryRun) {
            console.log("  --- Slack Message Preview ---");
            console.log(`  Text: ${message.text}`);
            console.log();
            for (const block of message.blocks ?? []) {
                if (block.type === "markdown") {
                    console.log(`  [markdown] ${block.text}`);
                    continue;
                }
                if (block.text) {
                    console.log(`  [${block.type}] ${block.text.text}`);
                }
                if (block.fields) {
                    for (const field of block.fields) {
                        console.log(`    [field] ${field.text}`);
                    }
                }
                if (block.elements) {
                    for (const el of block.elements) {
                        // Buttons carry `text` as a nested object plus a `url`; context
                        // text elements carry `text` as a plain mrkdwn/plain_text string;
                        // overflow elements have no `text` at all.
                        let label = "";
                        if ("url" in el) {
                            label = `${el.text.text} (${el.url})`;
                        }
                        else if ("text" in el) {
                            label = typeof el.text === "string" ? el.text : el.text.text;
                        }
                        console.log(`    [element] ${label}`);
                    }
                }
            }
            console.log();
            return;
        }
        // Deliver via Slack
        const webhookUrl = digestConfig?.slackWebhookUrl ?? process.env.SLACK_WEBHOOK_URL;
        if (!webhookUrl) {
            console.warn("  ⚠️  No Slack webhook URL configured. Set SLACK_WEBHOOK_URL or configure in schedules.yaml");
            console.log("  Printing digest to stdout instead:");
            console.log();
            console.log(`  ${message.text}`);
            return;
        }
        console.log("  Sending to Slack...");
        try {
            const response = await fetch(webhookUrl, {
                body: JSON.stringify(message),
                headers: { "Content-Type": "application/json" },
                method: "POST",
            });
            if (response.ok) {
                console.log("  ✅ Digest sent successfully");
            }
            else {
                const text = await response.text();
                console.warn(`  ⚠️  Slack delivery failed: ${response.status} ${text}`);
            }
        }
        catch (error) {
            console.warn(`  ⚠️  Slack delivery error: ${error instanceof Error ? error.message : String(error)}`);
        }
    });
}
