/**
 * Session Start Hook
 * Loads relevant memory and context when a session begins
 */
import { PLUGIN_VERSION } from '../config.js';
import { MemorySync } from '../memory/index.js';
import { getContextLoader } from '../session/context-loader.js';
let memorySync = null;
/**
 * Initialize memory sync engine
 */
export function initMemorySync(api) {
    if (!memorySync) {
        memorySync = new MemorySync(api);
        memorySync.init().catch(err => {
            api.logger.error(`[EO SessionStart] Failed to init memory sync: ${err}`);
        });
    }
    return memorySync;
}
/**
 * Get or create memory sync instance
 */
export function getMemorySync() {
    return memorySync;
}
export function createSessionStartHook(api) {
    return {
        id: 'eo_session_start',
        name: 'EO Session Start',
        description: 'Loads EO context and cross-session memory at session start',
        handle: async (event) => {
            api.logger.debug(`[EO SessionStart v${PLUGIN_VERSION}] Session hook fired`);
            try {
                // Initialize memory sync
                const sync = initMemorySync(api);
                // Extract session context from event
                const sessionId = event?.sessionId || event?.context?.sessionId || `session_${Date.now()}`;
                const userId = event?.context?.userId;
                const channel = event?.context?.channel;
                const context = {
                    sessionId,
                    userId,
                    channel,
                    api,
                };
                // Load relevant memory from global store
                const loaded = await sync.onSessionStart(context);
                // Build context to inject
                const injectedContext = {
                    recentTopics: loaded.recentMemories.map(m => m.key),
                    pendingTasks: loaded.tasks.map(t => t.taskId),
                    preferences: loaded.preferences,
                    projects: loaded.projects,
                    tasks: loaded.tasks,
                    lastSessionSummary: loaded.recentMemories[0]?.value,
                };
                api.logger.debug(`[EO SessionStart] Loaded ${loaded.recentMemories.length} recent memories, ${loaded.tasks.length} pending tasks`);
                // Store in event context for later use
                if (event?.context) {
                    event.context.eoMemory = injectedContext;
                }
                // ── Load Self-Evolution Learnings from MEMORY.md ──────────────────────
                // This loads the "🔄 自进化学习" section generated by DreamModule
                // and injects it into eoHistoricalContext for proactive awareness
                try {
                    const contextLoader = getContextLoader({
                        workspaceRoot: process.cwd(),
                    });
                    const selfEvolutionLearnings = contextLoader.loadSelfEvolutionLearnings();
                    if (selfEvolutionLearnings.length > 0) {
                        // Inject into event.context.eoHistoricalContext
                        event.context = event.context || {};
                        event.context.eoHistoricalContext = [
                            ...(event.context.eoHistoricalContext || []),
                            ...selfEvolutionLearnings,
                        ];
                        api.logger.debug(`[EO SessionStart] Loaded ${selfEvolutionLearnings.length} self-evolution learnings from MEMORY.md`);
                    }
                }
                catch (err) {
                    api.logger.warn(`[EO SessionStart] Failed to load self-evolution learnings: ${err}`);
                }
            }
            catch (error) {
                api.logger.error(`[EO SessionStart] Error loading memory: ${error}`);
            }
        },
    };
}
//# sourceMappingURL=session-start.js.map