import * as vscode from 'vscode';
import * as path from 'path';
import type { ChatMessage } from '../../agent';
import type { BrainProfile } from '../../config';
import { findBrainFiles } from '../../utils';
import {
    isExplicitSecondBrainRequest,
    isSecondBrainInventoryRequest,
} from '../../lib/contextBuilders/promptDetection';
import { buildSecondBrainInventoryContext } from '../../lib/contextBuilders/secondBrainInventory';
import { buildLocalProjectPathContext } from '../../lib/contextBuilders/localProjectPath';
import { buildRecentProjectKnowledgeContext } from '../../lib/contextBuilders/recentProjectKnowledge';
import { buildJarvisProjectBriefContext } from '../../lib/contextBuilders/jarvisProjectBrief';
import { buildAstraModeArchitectureContext } from '../../lib/contextBuilders/astraModeArchitecture';
import { buildSecondBrainTrace, SecondBrainTrace } from '../../features/secondBrainTrace';

export interface BuildTurnContextBlocksInput {
    prompt: string | null;
    options: any;  // the handlePrompt options object (we read secondBrainTraceEnabled, brainProfileId)
    isCasualConversation: boolean;
    loopDepth: number;
    config: any;  // getConfig() result — we read memoryLongTermFiles, maxContextSize, brainProfiles
    activeBrain: BrainProfile;
    chatHistory: ChatMessage[];
    rootPath: string;
}

export interface BuildTurnContextBlocksResult {
    contextBlock: string;
    brainContext: string;
    brainInventoryCtx: string;
    brainFiles: string[];
    brainPreview: string;
    localPathContext: string;
    secondBrainTrace: SecondBrainTrace | null;
}

export function buildTurnContextBlocks(input: BuildTurnContextBlocksInput): BuildTurnContextBlocksResult {
    const {
        prompt,
        options,
        isCasualConversation,
        loopDepth,
        config,
        activeBrain,
        chatHistory,
        rootPath,
    } = input;

    let contextBlock = '';
    const brainFiles = findBrainFiles(activeBrain.localBrainPath);
    let secondBrainTrace: SecondBrainTrace | null = null;
    if (options.secondBrainTraceEnabled && prompt && loopDepth === 0 && !isCasualConversation) {
        secondBrainTrace = buildSecondBrainTrace(prompt, activeBrain.localBrainPath, {
            force: isExplicitSecondBrainRequest(prompt),
            limit: Math.max(config.memoryLongTermFiles, 5)
        });
    }
    const brainPreview = brainFiles
        .slice(0, 30)
        .map(file => path.relative(activeBrain.localBrainPath, file))
        .join('\n');
    const brainContext = [
        `[ACTIVE SECOND BRAIN]`,
        `Use this Local Brain only when it is relevant to the user's current question.`,
        `Name: ${activeBrain.name}`,
        `Path: ${activeBrain.localBrainPath}`,
        `Knowledge files: ${brainFiles.length}`,
        activeBrain.description ? `Description: ${activeBrain.description}` : '',
        brainPreview ? `Available file examples:\n${brainPreview}` : 'Files: none found'
    ].filter(Boolean).join('\n');
    const brainInventoryCtx = prompt && !isCasualConversation && isSecondBrainInventoryRequest(prompt)
        ? `\n\n${buildSecondBrainInventoryContext(activeBrain, brainFiles)}`
        : '';
    const editor = vscode.window.activeTextEditor;
    if (editor && editor.document.uri.scheme === 'file') {
        const text = editor.document.getText();
        const name = path.basename(editor.document.fileName);
        if (text.trim().length > 0 && text.length < config.maxContextSize) {
            contextBlock = `\n\n[Currently open file: ${name}]\n\`\`\`\n${text}\n\`\`\``;
        }
    }
    const localPathContext = prompt && loopDepth === 0
        ? buildLocalProjectPathContext(prompt, rootPath)
        : '';
    if (localPathContext) {
        contextBlock += `\n\n${localPathContext}`;
    }
    const recentProjectKnowledgeContext = prompt && loopDepth === 0 && !isCasualConversation && !localPathContext
        ? buildRecentProjectKnowledgeContext(prompt, rootPath, chatHistory)
        : '';
    if (recentProjectKnowledgeContext) {
        contextBlock += `\n\n${recentProjectKnowledgeContext}`;
    }
    const projectBriefContext = prompt && loopDepth === 0 && !isCasualConversation
        ? buildJarvisProjectBriefContext(prompt, localPathContext, recentProjectKnowledgeContext)
        : '';
    if (projectBriefContext) {
        contextBlock += `\n\n${projectBriefContext}`;
    }
    const modeArchitectureContext = prompt && loopDepth === 0 && !isCasualConversation
        ? buildAstraModeArchitectureContext(prompt)
        : '';
    if (modeArchitectureContext) {
        contextBlock += `\n\n${modeArchitectureContext}`;
    }

    return {
        contextBlock,
        brainContext,
        brainInventoryCtx,
        brainFiles,
        brainPreview,
        localPathContext,
        secondBrainTrace,
    };
}
