import * as vscode from 'vscode';
import { logError, logInfo, resolveEngine } from '../../utils';
import { getConfig } from '../../config';
import type { ChatMessage } from '../../agent';

export interface CompressSummaryDeps {
    context: vscode.ExtensionContext;
    callNonStreaming: (params: {
        baseUrl: string;
        modelName: string;
        engine: 'lmstudio' | 'ollama';
        messages: ChatMessage[];
        temperature: number;
        maxTokens?: number;
        contextLength?: number;
        signal?: AbortSignal;
    }) => Promise<{ text: string; stopReason?: string }>;
}

export async function compressSessionSummary(deps: CompressSummaryDeps, taskId: string, history: ChatMessage[]): Promise<void> {
    const visible = history.filter((m) => !m.internal && (m.role === 'user' || m.role === 'assistant'));
    if (visible.length < 3) return;
    const cfg = getConfig();
    const transcript = visible
        .map((m) => `${m.role.toUpperCase()}: ${String(m.content).replace(/\s+/g, ' ').slice(0, 400)}`)
        .join('\n\n');
    const messages: ChatMessage[] = [
        {
            role: 'system',
            content: [
                'You compress chat transcripts into a 2-3 sentence summary.',
                'Capture: (1) the user\'s topic or task, (2) the main decision or answer reached, (3) any open issue.',
                'Reply in the user\'s primary language (mirror Korean ↔ English exactly as in the transcript).',
                'Reply with ONLY the summary text. No headers, no quotes, no preamble.',
            ].join(' '),
            internal: true,
        },
        { role: 'user', content: `[TRANSCRIPT]\n${transcript}\n[END]` },
    ];
    try {
        const result = await deps.callNonStreaming({
            baseUrl: cfg.ollamaUrl,
            modelName: cfg.defaultModel,
            engine: resolveEngine(cfg.ollamaUrl),
            messages,
            temperature: 0.3,
            maxTokens: 256,
            contextLength: cfg.contextLength,
        });
        const summary = (result.text || '').trim().replace(/^["'`]+|["'`]+$/g, '');
        if (!summary || summary.length < 12) return;
        const sessions = deps.context.globalState.get<any[]>('chat_sessions', []) || [];
        const idx = sessions.findIndex((s) => String(s?.id) === String(taskId));
        if (idx < 0) return;
        sessions[idx].summary = summary;
        await deps.context.globalState.update('chat_sessions', sessions);
        logInfo('Session summary stored for medium-term recall.', { taskId, length: summary.length });
    } catch (e: any) {
        logError('Session summary compression failed.', { taskId, error: e?.message ?? String(e) });
    }
}
