/**
 * Workspace Brain — local codebase index + Brain Hub sync for CLI.
 */
import * as path from 'path';
import { BrainHubClient } from './brain-hub-client.js';
import { CodebaseIndexer } from './codebase-indexer.js';
export class WorkspaceBrainService {
    workspacePath;
    indexer;
    brainClient;
    autoIndex;
    brainSyncEnabled;
    accountContextCache = null;
    constructor(options) {
        this.workspacePath = path.resolve(options.workspacePath);
        this.indexer = new CodebaseIndexer(this.workspacePath);
        this.brainClient = new BrainHubClient({
            apiBase: options.apiBase,
            getAuthToken: options.getAuthToken,
        });
        this.autoIndex = options.autoIndex ?? !/^(1|true|yes)$/i.test(String(process.env.VIGTHORIA_NO_AUTO_INDEX || ''));
        this.brainSyncEnabled = options.brainSyncEnabled ?? !/^(1|true|yes)$/i.test(String(process.env.VIGTHORIA_NO_BRAIN_SYNC || ''));
    }
    getIndexer() {
        return this.indexer;
    }
    getStatus() {
        const status = this.indexer.getStatus();
        return {
            workspacePath: this.workspacePath,
            indexedFileCount: status.indexedFileCount,
            totalChunks: status.totalChunks,
            isIndexing: status.isIndexing,
            meta: CodebaseIndexer.loadMeta(this.workspacePath),
        };
    }
    async ensureIndexed(options = {}) {
        if (this.indexer.hasLocalIndex() && this.indexer.getStatus().totalChunks === 0) {
            const meta = await this.indexer.indexWorkspace();
            await this.syncIndexToHub(meta);
            return { indexed: true, fileCount: meta.indexedFileCount, chunkCount: meta.totalChunks };
        }
        if (this.indexer.hasLocalIndex()) {
            const meta = CodebaseIndexer.loadMeta(this.workspacePath);
            return {
                indexed: true,
                fileCount: meta?.indexedFileCount || this.indexer.getStatus().indexedFileCount,
                chunkCount: meta?.totalChunks || this.indexer.getStatus().totalChunks,
            };
        }
        if (!this.autoIndex && !options.promptIfMissing) {
            return { indexed: false, fileCount: 0, chunkCount: 0, prompted: 'skipped' };
        }
        if (options.promptIfMissing && options.askToIndex) {
            const wsName = path.basename(this.workspacePath);
            const fileCount = this.indexer.countIndexableFiles();
            if (fileCount === 0) {
                return { indexed: false, fileCount: 0, chunkCount: 0, prompted: 'skipped' };
            }
            const choice = await options.askToIndex(fileCount, wsName);
            if (choice === 'later') {
                return { indexed: false, fileCount: 0, chunkCount: 0, prompted: 'later' };
            }
        }
        const meta = await this.indexer.indexWorkspace();
        await this.syncIndexToHub(meta);
        return {
            indexed: true,
            fileCount: meta.indexedFileCount,
            chunkCount: meta.totalChunks,
            prompted: options.promptIfMissing ? 'index_now' : undefined,
        };
    }
    async reindexWorkspace() {
        const meta = await this.indexer.indexWorkspace();
        await this.syncIndexToHub(meta);
        return meta;
    }
    buildCodebaseContext(prompt) {
        if (!prompt.trim() || !this.indexer.hasLocalIndex()) {
            return '';
        }
        const context = this.indexer.getContextForQuery(prompt, 3500);
        if (!context) {
            return '';
        }
        return `Vigthoria codebase index context.\n${context}`;
    }
    searchCodebase(query, maxResults = 30) {
        return this.indexer.formatSearchResults(query, maxResults);
    }
    async fetchAccountBrainContext(force = false) {
        if (!this.brainSyncEnabled) {
            return '';
        }
        const cacheTtlMs = 5 * 60 * 1000;
        if (!force && this.accountContextCache && Date.now() - this.accountContextCache.fetchedAt < cacheTtlMs) {
            return this.accountContextCache.text;
        }
        const response = await this.brainClient.fetchAccountContext(25);
        const text = String(response.formattedText || '').trim();
        this.accountContextCache = { text, fetchedAt: Date.now() };
        return text;
    }
    async syncIndexToHub(meta) {
        if (!this.brainSyncEnabled) {
            return;
        }
        const wsName = path.basename(this.workspacePath);
        const summary = `Workspace "${wsName}" indexed in Vigthoria CLI: ${meta.indexedFileCount} files, ${meta.totalChunks} chunks. Key paths: ${meta.topFiles.slice(0, 6).join(', ')}`;
        await this.brainClient.syncWorkspaceIndex({
            workspaceName: wsName,
            workspacePath: this.workspacePath,
            fileCount: meta.indexedFileCount,
            chunkCount: meta.totalChunks,
            topFiles: meta.topFiles,
            summary,
            indexHash: meta.indexHash,
        }).catch(() => undefined);
    }
}
