/**
 * TaskFileLoader — loads task definitions from TypeScript files.
 *
 * Supports `*.task.ts` and `*.task.js` files in task directories. Files
 * are loaded via jiti and expected to export GeneralizedTaskDefinition
 * objects authored with `defineTask()`.
 *
 * TS task files export a single task or an array of tasks:
 *
 * ```typescript
 * // single task
 * import { defineTask } from "@sanity/ailf"
 * export default defineTask({ id: "my-task", mode: "literacy", ... })
 *
 * // multiple tasks
 * export default [
 *   defineTask({ id: "task-1", mode: "literacy", ... }),
 *   defineTask({ id: "task-2", mode: "literacy", ... }),
 * ]
 * ```
 *
 * @see docs/design-docs/architecture-overhaul/typescript-configuration.md
 */
import { existsSync, readdirSync } from "fs";
import { pathToFileURL } from "node:url";
import { resolve } from "path";
import { createJiti } from "jiti";
import { resolveAilfAlias } from "../config-sources/ailf-resolver.js";
import { loadTsConfig } from "../config-sources/ts-config-loader.js";
/**
 * Discover TS/JS task files in a directory.
 *
 * Looks for files matching `*.task.ts` or `*.task.js`.
 *
 * @param tasksDir - Absolute path to the tasks directory
 * @returns Array of absolute file paths
 */
export function discoverTsTaskFiles(tasksDir) {
    if (!existsSync(tasksDir))
        return [];
    return readdirSync(tasksDir)
        .filter((f) => (f.endsWith(".task.ts") || f.endsWith(".task.js")) && !f.startsWith("."))
        .sort()
        .map((f) => resolve(tasksDir, f));
}
/**
 * Load task definitions from a single TS/JS task file.
 *
 * The file's default export can be:
 * - A single task object → wrapped in an array
 * - An array of task objects → used as-is
 *
 * Returns the raw task data without validation — the caller is
 * responsible for running the result through Zod schemas.
 *
 * @param filePath - Absolute path to the .task.ts or .task.js file
 * @returns The loaded task(s), or throws on load failure
 */
export async function loadTsTaskFile(filePath) {
    const result = await loadTsConfig(filePath);
    if (!result.ok) {
        throw new Error(result.error);
    }
    const value = result.value;
    // Normalize: single object → array of one
    const tasks = Array.isArray(value) ? value : [value];
    return { filePath, tasks };
}
/**
 * Synchronously load task definitions from a single TS/JS task file.
 *
 * Uses jiti's synchronous require-style loading instead of async import().
 * Needed by resolve-mappings.ts which is called from sync contexts.
 */
export function loadTsTaskFileSync(filePath) {
    const alias = resolveAilfAlias(filePath);
    const jiti = createJiti(pathToFileURL(filePath).href, {
        interopDefault: true,
        requireCache: true,
        ...(alias ? { alias } : {}),
    });
    const mod = jiti(filePath);
    const value = mod && typeof mod === "object" && "default" in mod ? mod.default : mod;
    const tasks = Array.isArray(value) ? value : [value];
    return { filePath, tasks };
}
/**
 * Load all TS task files from a directory.
 *
 * @param tasksDir - Absolute path to the tasks directory
 * @returns Array of raw task data from all files
 */
export async function loadAllTsTaskFiles(tasksDir) {
    const files = discoverTsTaskFiles(tasksDir);
    const results = [];
    for (const file of files) {
        results.push(await loadTsTaskFile(file));
    }
    return results;
}
