/**
 * lookup-doc command — search Sanity for documentation articles by keyword.
 *
 * Helps external contributors find the correct `slug` for contextDocs
 * references without needing to browse the CMS or guess from URLs.
 *
 * Usage:
 *   ailf lookup-doc webhooks
 *   ailf lookup-doc "visual editing"
 *   ailf lookup-doc groq --limit 20
 *
 * @see docs/design-docs/canonical-doc-resolution.md
 */
import { Command } from "commander";
export function createLookupDocCommand() {
    return new Command("lookup-doc")
        .description("Search Sanity docs by keyword — find slugs for contextDocs references")
        .argument("<keyword>", "Search keyword (matches title and slug)")
        .option("-l, --limit <n>", "Maximum results to show", parseInt, 10)
        .option("-s, --source <name>", "Documentation source (from sources.yaml)")
        .action(async (keyword, opts) => {
        const { getSanityClient } = await import("../sanity/client.js");
        const { loadSource } = await import("../sources.js");
        // Resolve source if provided
        let clientOverrides;
        if (opts.source) {
            try {
                const source = loadSource(opts.source);
                clientOverrides = {};
                if (source.dataset)
                    clientOverrides.dataset = source.dataset;
                if (source.projectId)
                    clientOverrides.projectId = source.projectId;
            }
            catch (err) {
                const msg = err instanceof Error ? err.message : String(err);
                console.error(`❌ Failed to load source "${opts.source}": ${msg}`);
                process.exit(1);
            }
        }
        const client = getSanityClient(clientOverrides);
        const escapedKeyword = keyword.replace(/"/g, '\\"');
        console.log(`\nSearching for "${keyword}"...\n`);
        const query = `*[_type == "article"
          && !(_id in path("drafts.**"))
          && (
            title match "*${escapedKeyword}*"
            || slug.current match "*${escapedKeyword}*"
          )
        ] | order(title asc) [0...$limit] {
          title,
          "slug": slug.current,
          "section": primarySection->title,
          "sectionSlug": primarySection->slug.current
        }`;
        const results = await client.fetch(query, {
            limit: opts.limit,
        });
        if (results.length === 0) {
            console.log(`  No articles found matching "${keyword}".\n\n` +
                "  Tips:\n" +
                "  - Try a shorter or more general keyword\n" +
                "  - Use partial matches (e.g., 'webhook' instead of 'webhooks')\n");
            process.exit(0);
        }
        console.log(`  Found ${results.length} article${results.length === 1 ? "" : "s"}:\n`);
        // Find longest slug for alignment
        const maxSlugLen = Math.min(40, Math.max(...results.map((r) => r.slug.length)));
        for (const doc of results) {
            const section = doc.section ?? "Unknown";
            const paddedSlug = doc.slug.padEnd(maxSlugLen);
            console.log(`  slug: ${paddedSlug}  │ ${doc.title}`);
            console.log(`  ${"".padEnd(maxSlugLen + 6)}  │ Section: ${section}\n`);
        }
        console.log("  Usage in .ailf/tasks/*.yaml:\n");
        console.log("  contextDocs:");
        console.log(`    - slug: ${results[0].slug}`);
        console.log(`      reason: "${results[0].title}"`);
        if (results[0].sectionSlug) {
            console.log(`\n  Or use path: ${results[0].sectionSlug}/${results[0].slug}`);
        }
        console.log();
    });
}
