/**
 * studiograph index command
 *
 * Bulk-indexes all entities across the workspace into LanceDB.
 * On first run, optionally prompts for a Voyage AI API key to enable
 * semantic search (Tier 2). Without a key, FTS-only indexing still runs.
 *
 * Safe to re-run — uses upsert, not insert.
 *
 * Usage:
 *   studiograph index              # index all repos
 *   studiograph index --repo raa   # single repo only
 */
import { Command } from 'commander';
import { join } from 'path';
import { homedir } from 'os';
import { select, text, spinner, log, outro } from '@clack/prompts';
import { Workspace } from '../../core/workspace.js';
import { loadUserConfig, saveUserConfig } from '../../core/user-config.js';
import { VectorService } from '../../services/vector-service.js';
import { AssetIndexService } from '../../services/assets/asset-index-service.js';
import { BaseGraphManager } from '../../core/graph.js';
export const indexCommand = new Command('index')
    .description('Index workspace entities for search (FTS + optional semantic search)')
    .option('--repo <name>', 'Index a single repo only')
    .action(async (opts) => {
    const workspace = new Workspace();
    if (!workspace.isWorkspace()) {
        console.error('❌ Not a Studiograph workspace. Run `studiograph init` first.');
        process.exit(1);
    }
    const config = await workspace.loadConfig();
    const userConfig = loadUserConfig();
    // First-run: prompt for Voyage AI key if not configured
    if (!userConfig.voyage_api_key) {
        const choice = await select({
            message: 'Enable semantic search? (optional — requires a Voyage AI API key)',
            options: [
                {
                    value: 'skip',
                    label: 'Skip — use keyword/FTS search only',
                    hint: 'Free, no setup required',
                },
                {
                    value: 'voyage',
                    label: 'Enable semantic search',
                    hint: 'Voyage AI key required — get one at voyageai.com',
                },
            ],
        });
        if (typeof choice === 'symbol') {
            outro('Cancelled');
            process.exit(0);
        }
        if (choice === 'voyage') {
            const keyInput = await text({
                message: 'Enter your Voyage AI API key:',
                placeholder: 'pa-...',
                validate: (value) => {
                    if (!value || value.length < 10)
                        return 'Key seems too short';
                },
            });
            if (typeof keyInput !== 'string') {
                outro('Cancelled');
                process.exit(0);
            }
            userConfig.voyage_api_key = keyInput;
            saveUserConfig(userConfig);
            log.success('Voyage AI key saved');
        }
    }
    const dbPath = userConfig.vector_db_path || join(homedir(), '.studiograph', 'vector');
    const vectorService = new VectorService(dbPath, userConfig.voyage_api_key);
    // Wire the assets.db handle so reindex folds embedded-image captions into
    // entry search text (parity with the server's incremental reindex).
    vectorService.setAssetIndex(new AssetIndexService(workspace.getWorkspacePath()));
    await vectorService.init();
    const repos = opts.repo
        ? config.repos.filter(r => r.name === opts.repo)
        : config.repos;
    if (opts.repo && repos.length === 0) {
        console.error(`❌ Repo "${opts.repo}" not found in workspace`);
        process.exit(1);
    }
    const s = spinner();
    let totalIndexed = 0;
    let totalWithVectors = 0;
    for (const repo of repos) {
        const repoPath = join(workspace.getWorkspacePath(), repo.path);
        s.start(`Indexing ${repo.name}...`);
        try {
            const graph = new BaseGraphManager({
                repoPath,
                repoName: repo.name,
                gitUser: { id: 'index', name: 'index', email: 'index@studiograph.local' },
            });
            const entities = graph.list();
            if (entities.length === 0) {
                s.stop(`${repo.name}: no entities`);
                vectorService.setLastIndexedTime(repo.name);
                continue;
            }
            s.message(`Indexing ${repo.name}: ${entities.length} entities...`);
            await vectorService.upsertMany(repo.name, entities);
            vectorService.setLastIndexedTime(repo.name);
            const withVectors = userConfig.voyage_api_key ? entities.length : 0;
            totalIndexed += entities.length;
            totalWithVectors += withVectors;
            s.stop(`${repo.name}: indexed ${entities.length} entities`);
        }
        catch (err) {
            s.stop(`${repo.name}: failed — ${err instanceof Error ? err.message : 'unknown error'}`);
        }
    }
    const vectorNote = userConfig.voyage_api_key
        ? ` (${totalWithVectors} with semantic vectors)`
        : ' (FTS only — add voyage_api_key to enable semantic search)';
    outro(`✓ Indexed ${totalIndexed} entities across ${repos.length} folder${repos.length === 1 ? '' : 's'}${vectorNote}`);
});
//# sourceMappingURL=index.js.map