#!/usr/bin/env tsx
/**
 * Migration script: Add mode: "literacy" to Content Lake task documents.
 *
 * Phase 7f of the Architecture Overhaul. Queries all ailf.task documents
 * that lack an explicit `mode` field and patches them with
 * `mode: "literacy"` (the default mode for existing tasks).
 *
 * Idempotent — the GROQ query only matches documents where
 * `!defined(mode)`, so re-running has no effect on already-patched
 * documents.
 *
 * Usage:
 *   cd packages/eval
 *   npx tsx src/scripts/migrate-task-mode.ts --dry-run
 *   npx tsx src/scripts/migrate-task-mode.ts
 *
 * Prerequisites:
 *   - SANITY_API_TOKEN with write access to the project
 *   - SANITY_PROJECT_ID and SANITY_DATASET configured (or defaults used)
 *
 * @see docs/archive/exec-plans/architecture-overhaul/phase-7-migrate-literacy.md
 */
import { config as dotenvConfig } from "dotenv";
import { existsSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
import { getSanityClient } from "../sanity/client.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..", "..");
// Load .env from repository root (same as CLI entry point)
const envPath = resolve(ROOT, "..", "..", ".env");
if (existsSync(envPath)) {
    dotenvConfig({ override: true, path: envPath });
}
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
const DRY_RUN = process.argv.includes("--dry-run");
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
async function main() {
    console.log("╭──────────────────────────────────────────────╮");
    console.log('│ Phase 7f: Migrate task mode → "literacy"      │');
    console.log("╰──────────────────────────────────────────────╯");
    console.log();
    if (DRY_RUN) {
        console.log("  🏷️  DRY RUN — no documents will be modified.\n");
    }
    const client = getSanityClient({
        token: process.env.AILF_REPORT_SANITY_API_TOKEN || process.env.SANITY_API_TOKEN,
    });
    // Step 1: Find all ailf.task documents without an explicit mode
    const query = `*[_type == "ailf.task" && !defined(mode)]{ _id, title }`;
    const tasksWithoutMode = await client.fetch(query);
    console.log(`  Found ${tasksWithoutMode.length} task(s) without an explicit mode.\n`);
    if (tasksWithoutMode.length === 0) {
        console.log("  ✅ Nothing to migrate — all tasks already have a mode.");
        return;
    }
    // Step 2: Show what would be patched
    for (const task of tasksWithoutMode) {
        const label = task.title ?? task._id;
        console.log(`    • ${label} (${task._id})`);
    }
    console.log();
    if (DRY_RUN) {
        console.log(`  Would patch ${tasksWithoutMode.length} document(s) with mode: "literacy".`);
        console.log("  Re-run without --dry-run to apply.\n");
        return;
    }
    // Step 3: Patch all matching documents in a transaction
    const transaction = client.transaction();
    for (const task of tasksWithoutMode) {
        transaction.patch(task._id, (patch) => patch.set({ mode: "literacy" }));
    }
    const result = await transaction.commit();
    console.log(`  ✅ Patched ${tasksWithoutMode.length} document(s) with mode: "literacy".`);
    console.log(`  Transaction ID: ${result.transactionId}\n`);
}
main().catch((err) => {
    console.error("Migration failed:", err);
    process.exit(1);
});
