/**
 * pipeline/resolve-mappings.ts
 *
 * Extracts canonical mappings from task definitions (*.task.ts files).
 * Each task contains context.docs and referenceSolution fields
 * directly — there is no separate mappings file.
 *
 * The output shape matches what downstream consumers expect so
 * fetch-docs, validate, and calculate-scores work without changes.
 */
import { existsSync } from "fs";
import { discoverTsTaskFiles, loadTsTaskFileSync, } from "../adapters/task-sources/task-file-loader.js";
import { resolveVendoredSubdir } from "./compiler/config-loader.js";
// ---------------------------------------------------------------------------
// Resolution
// ---------------------------------------------------------------------------
/**
 * Extract canonical mappings from *.task.ts files in tasks/literacy/.
 * Only tasks with context.docs and referenceSolution are included.
 */
export function extractInlineMappings(rootDir) {
    const tasksDir = resolveVendoredSubdir(rootDir, "tasks/literacy");
    const result = { feature_areas: {} };
    if (!existsSync(tasksDir))
        return result;
    const files = discoverTsTaskFiles(tasksDir);
    for (const file of files) {
        const loaded = loadTsTaskFileSync(file);
        for (const task of loaded.tasks) {
            const t = task;
            const area = typeof t.area === "string" ? t.area : undefined;
            const id = typeof t.id === "string" ? t.id : undefined;
            const title = typeof t.title === "string" ? t.title : "";
            const referenceSolution = typeof t.referenceSolution === "string" ? t.referenceSolution : "";
            if (!area || !id)
                continue;
            // Extract docs from context.docs (GeneralizedDocRef[])
            const context = t.context;
            const docs = [];
            if (context?.docs && Array.isArray(context.docs)) {
                for (const doc of context.docs) {
                    const d = doc;
                    if (typeof d.slug === "string") {
                        docs.push({
                            slug: d.slug,
                            reason: typeof d.reason === "string" ? d.reason : "",
                        });
                    }
                }
            }
            if (docs.length === 0 || !referenceSolution)
                continue;
            if (!result.feature_areas[area]) {
                result.feature_areas[area] = { tasks: [] };
            }
            result.feature_areas[area].tasks.push({
                canonical_docs: docs,
                description: title,
                id,
                reference_solution: referenceSolution,
            });
        }
    }
    return result;
}
/**
 * Resolve canonical mappings from task definitions.
 * This is the single source of truth — there is no external mappings file.
 */
export function resolveMappings(rootDir) {
    return extractInlineMappings(rootDir);
}
