import type { ChatMessage } from '../../agent';
import { computeModeSignature } from '../../lib/contextBuilders/systemPromptShaping';
import { buildLastTopicLine } from '../../lib/contextBuilders/lastTopicLine';
import { getActiveBrainProfile, logError } from '../../utils';

export interface BuildModeBridgeContextInput {
    options: any;  // the handlePrompt options object
    lastModeSignature: string | null;
    chatHistory: ChatMessage[];
}

export interface BuildModeBridgeContextResult {
    /** "[MODE TRANSITION BRIDGE]\n…" string to embed in system prompt, or '' when no transition. */
    modeBridgeCtx: string;
    /** The newly-computed signature — caller should store this as the next-turn comparison baseline. */
    newSignature: string | null;
}

export function buildModeBridgeContext(input: BuildModeBridgeContextInput): BuildModeBridgeContextResult {
    const { options, lastModeSignature, chatHistory } = input;

    // v2.2.69 — 모드 전환 bridge. 현재 mode signature 를 직전 값과 비교해 바뀌었으면
    // "이전 대화는 X 모드에서 Y 주제로 진행됨 / 지금부터 Z 모드" 한 줄을 system prompt 에 끼운다.
    // chatHistory 자체는 손대지 않으므로 사용자 입장에선 대화가 연속되어 보이면서도
    // 모델은 "모드가 바뀐 직후" 임을 인지한다.
    let modeBridgeCtx = '';
    let newSignature: string | null = null;
    try {
        const agentSkillName = options.agentSkillContext
            ? (options.agentSkillContext.split('\n')[0] || '').slice(0, 60).replace(/^#\s*/, '').trim()
            : '';
        const currentSig = computeModeSignature({
            agentSkillName: agentSkillName || undefined,
            companyMode: !!(options as any).companyMode,
            multiAgent: !!(options as any).multiAgent,
            brainName: getActiveBrainProfile()?.name,
        });
        if (lastModeSignature !== null && lastModeSignature !== currentSig) {
            const topic = buildLastTopicLine(chatHistory);
            const bridgeLines = [
                '',
                '[MODE TRANSITION BRIDGE]',
                `이전 모드: ${lastModeSignature}`,
                `현재 모드: ${currentSig}`,
            ];
            if (topic) bridgeLines.push(`직전 대화 주제(한 줄): ${topic}`);
            bridgeLines.push('대화 history 는 그대로 이어진다. 새 모드의 페르소나/포맷을 따르되, 직전까지 사용자가 다루던 맥락을 잊지 말 것.');
            modeBridgeCtx = bridgeLines.join('\n');
        }
        newSignature = currentSig;
    } catch (e: any) {
        logError('Mode-bridge computation failed (non-fatal).', { error: e?.message || String(e) });
        return { modeBridgeCtx: '', newSignature: null };
    }

    return { modeBridgeCtx, newSignature };
}
