"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var CacheInvalidationService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheInvalidationService = void 0;
const common_1 = require("@nestjs/common");
const etag_cache_service_1 = require("./etag-cache.service");
const application_state_service_1 = require("../../application-state/application-state.service");
let CacheInvalidationService = CacheInvalidationService_1 = class CacheInvalidationService {
    constructor(etagCacheService, applicationStateService) {
        this.etagCacheService = etagCacheService;
        this.applicationStateService = applicationStateService;
        this.logger = new common_1.Logger(CacheInvalidationService_1.name);
        CacheInvalidationService_1.instance = this;
    }
    static getInstance() {
        return CacheInvalidationService_1.instance;
    }
    async invalidateEntity(entityType, context = {}) {
        const patterns = await this.getPatternsForEntity(entityType, context);
        for (const pattern of patterns) {
            this.etagCacheService.invalidatePattern(pattern);
        }
        this.logger.log(`Cache invalidation complete for ${entityType}: ${patterns.length} patterns`);
    }
    async getPatternsForEntity(entityType, context) {
        if (context.sessionId && context.isActive === undefined) {
            context.isActive = await this.checkIfActiveSession(context.sessionId);
        }
        switch (entityType) {
            case 'session':
                return this.getSessionPatterns(context);
            case 'session_input':
                return this.getSessionInputPatterns(context);
            case 'ai_action':
                return this.getAIActionPatterns(context);
            case 'execution_log':
                return this.getExecutionLogPatterns(context);
            case 'context_template':
                return this.getContextTemplatePatterns(context);
            case 'system_prompt':
                return this.getSystemPromptPatterns(context);
            case 'custom_snippet':
                return ['/custom-snippets*'];
            case 'context_snippet':
                return ['/context-snippets*'];
            case 'custom_variable':
                return ['/custom-variables*'];
            case 'project':
                return this.getProjectPatterns(context);
            case 'tool_hook':
                return ['/tool-hooks*', '/system-prompts*'];
            case 'mcp_config':
                return ['/mcp-configs*', '/mcp-tools*', '/system-prompts*'];
            case 'sub_agent':
                return ['/sub-agents*', '/sessions*'];
            case 'application_state':
                return this.getApplicationStatePatterns(context);
            case 'llm_call_log':
                return ['/llm-call-logs*'];
            default:
                return [];
        }
    }
    getSessionPatterns(context) {
        const patterns = ['/sessions*'];
        if (context.sessionId) {
            patterns.push(`/sessions/${context.sessionId}*`);
        }
        if (context.isActive) {
            patterns.push('/sessions/active*');
        }
        patterns.push('/application-state*');
        return patterns;
    }
    getSessionInputPatterns(context) {
        const patterns = [];
        if (context.sessionId) {
            patterns.push(`/sessions/${context.sessionId}*`);
        }
        patterns.push('/sessions*');
        if (context.isActive) {
            patterns.push('/sessions/active*');
        }
        return patterns;
    }
    getAIActionPatterns(context) {
        const patterns = [];
        if (context.sessionId) {
            patterns.push(`/sessions/${context.sessionId}*`);
        }
        patterns.push('/sessions*');
        if (context.isActive) {
            patterns.push('/sessions/active*');
        }
        patterns.push('/ai-actions*');
        return patterns;
    }
    getExecutionLogPatterns(context) {
        const patterns = [];
        if (context.sessionId) {
            patterns.push(`/sessions/${context.sessionId}*`);
        }
        if (context.isActive) {
            patterns.push('/sessions/active*');
        }
        return patterns;
    }
    getContextTemplatePatterns(_context) {
        const patterns = ['/context-templates*'];
        patterns.push('/sessions*');
        return patterns;
    }
    getSystemPromptPatterns(_context) {
        return ['/system-prompts*', '/sessions*', '/sub-agents*'];
    }
    getProjectPatterns(_context) {
        return ['/projects*', '/sessions*'];
    }
    getApplicationStatePatterns(context) {
        const patterns = ['/application-state*'];
        if (context.stateKey === 'activeSessionId') {
            patterns.push('/sessions*', '/sessions/active*');
        }
        return patterns;
    }
    async checkIfActiveSession(sessionId) {
        try {
            const activeSessionId = await this.applicationStateService.getActiveSessionId();
            return sessionId === activeSessionId;
        }
        catch (error) {
            this.logger.warn(`Could not check active session: ${error.message}. Assuming not active.`);
            return false;
        }
    }
    async invalidateEntities(entities) {
        const allPatterns = new Set();
        for (const { type, context } of entities) {
            const patterns = await this.getPatternsForEntity(type, context);
            patterns.forEach((p) => allPatterns.add(p));
        }
        for (const pattern of allPatterns) {
            this.etagCacheService.invalidatePattern(pattern);
        }
        this.logger.log(`Batch invalidation complete: ${allPatterns.size} unique patterns`);
    }
};
exports.CacheInvalidationService = CacheInvalidationService;
exports.CacheInvalidationService = CacheInvalidationService = CacheInvalidationService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => application_state_service_1.ApplicationStateService))),
    __metadata("design:paramtypes", [etag_cache_service_1.ETagCacheService,
        application_state_service_1.ApplicationStateService])
], CacheInvalidationService);
//# sourceMappingURL=cache-invalidation.service.js.map