/**
 * webhook/dispatch.ts
 *
 * Triggers AI Literacy Framework evaluations via GitHub Actions
 * repository_dispatch events.
 *
 * When a content webhook determines that a document change affects
 * tracked evaluation areas, this module dispatches a scoped pipeline
 * run to the AILF repository.
 *
 * The dispatch uses the `external-eval` event type. The client_payload
 * conforms to the PipelineRequestSchema so the receiving workflow can
 * pass it directly to the CLI via `--config` without field translation.
 *
 * @see .github/workflows/external-eval.yml
 * @see docs/design-docs/cross-repo-eval.md
 */
import { LiteracyVariant } from "../pipeline/normalize-mode.js";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const DEFAULT_REPO = "sanity-labs/ai-literacy-framework";
const GITHUB_API = "https://api.github.com";
/**
 * Dispatch an evaluation via GitHub Actions repository_dispatch.
 *
 * Sends a `repository_dispatch` event with the `external-eval` event type.
 * The payload includes area and task scoping so the pipeline evaluates
 * only what's needed.
 *
 * GitHub API response:
 * - 204: Dispatch accepted
 * - 404: Repository not found or token lacks access
 * - 422: Validation error
 */
export async function dispatchEvaluation(request, options) {
    const repo = options.repo ?? DEFAULT_REPO;
    const url = `${GITHUB_API}/repos/${repo}/dispatches`;
    const payload = {
        client_payload: {
            areas: request.areas,
            caller_repo: "ailf-webhook-handler",
            changedDocs: request.documentSlug
                ? request.documentSlug.split(",").filter(Boolean)
                : undefined,
            compare: true,
            mode: request.mode ?? LiteracyVariant.STANDARD,
            publish: true,
            source: "production",
            tasks: request.taskIds.length > 0 ? request.taskIds : undefined,
        },
        event_type: "external-eval",
    };
    try {
        const response = await fetch(url, {
            body: JSON.stringify(payload),
            headers: {
                Accept: "application/vnd.github+json",
                Authorization: `Bearer ${options.githubToken}`,
                "X-GitHub-Api-Version": "2022-11-28",
            },
            method: "POST",
        });
        if (response.status === 204) {
            return { httpStatus: 204, ok: true };
        }
        // Try to extract error message
        let error;
        try {
            const body = (await response.json());
            error = body.message ?? `HTTP ${response.status}`;
        }
        catch {
            error = `HTTP ${response.status}: ${response.statusText}`;
        }
        return { error, httpStatus: response.status, ok: false };
    }
    catch (err) {
        return {
            error: err instanceof Error ? err.message : String(err),
            httpStatus: 0,
            ok: false,
        };
    }
}
