import * as vscode from 'vscode';
import { getActiveBrainProfile, logError, logInfo } from '../utils';
import { BrainProfile, getConfig } from '../config';
import { SessionManager } from '../core/session';
import { ChatMessage } from '../agent';

export interface RestoreLastSessionDeps {
    sessionManager: SessionManager;
    setChatHistory: (history: ChatMessage[]) => void;
    setCurrentTaskId: (taskId: string) => void;
}

export async function restoreLastSession(deps: RestoreLastSessionDeps): Promise<void> {
    try {
        const lastSession = deps.sessionManager.loadLastActiveSession();
        if (lastSession) {
            deps.setChatHistory(lastSession.history);
            deps.setCurrentTaskId(lastSession.taskId);
            logInfo(`Restored last session: ${lastSession.taskId}`);
        }
    } catch (error) {
        logError('Failed to restore last session. Starting fresh.', error);
    }
}

export interface ExecuteActionTagsOnTextDeps {
    executeActions: (aiMessage: string, rootPath: string, activeBrain: BrainProfile) => Promise<string[]>;
}

export async function executeActionTagsOnText(
    deps: ExecuteActionTagsOnTextDeps,
    aiMessage: string
): Promise<string[]> {
    const cfg = getConfig();
    const rootPath = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath
        || cfg.localBrainPath
        || process.cwd();
    const activeBrain = getActiveBrainProfile();
    try {
        return await deps.executeActions(aiMessage, rootPath, activeBrain);
    } catch (e: any) {
        logError('executeActionTagsOnText failed.', { error: e?.message ?? String(e) });
        return [`❌ Action 실행 중 오류: ${e?.message ?? e}`];
    }
}

export function syncBrain(brainDir: string): void {
    try {
        const { execSync } = require('child_process');
        execSync(`git add .`, { cwd: brainDir });
        execSync(`git commit -m "[Astra] Knowledge Update"`, { cwd: brainDir });
        execSync(`git push`, { cwd: brainDir });
    } catch (err) {
        logError('Second Brain sync failed.', err);
    }
}
