"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 FrontendNotificationHook_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrontendNotificationHook = void 0;
const common_1 = require("@nestjs/common");
const events_gateway_1 = require("../../events/events.gateway");
const application_state_service_1 = require("../../application-state/application-state.service");
const notifications_service_1 = require("../../notifications/notifications.service");
const sessions_service_1 = require("../../sessions/sessions.service");
const app_service_1 = require("../../app.service");
const chat_service_1 = require("../../interactive-chat/chat.service");
const os_1 = require("os");
let FrontendNotificationHook = FrontendNotificationHook_1 = class FrontendNotificationHook {
    constructor(eventsGateway, applicationStateService, notificationsService, sessionsService, appService, chatService) {
        this.eventsGateway = eventsGateway;
        this.applicationStateService = applicationStateService;
        this.notificationsService = notificationsService;
        this.sessionsService = sessionsService;
        this.appService = appService;
        this.chatService = chatService;
        this.logger = new common_1.Logger(FrontendNotificationHook_1.name);
    }
    async run(sessionInput, context) {
        if (context.flags.follow_up_initiated) {
            this.logger.log('Skipping frontend notification because a follow-up action was initiated.');
            return;
        }
        this.logger.log('Notifying frontend that plan is ready for review.');
        this.eventsGateway.sendToAll('plan-ready', {
            sessionId: sessionInput.session_id,
            sessionInputId: sessionInput.id,
        });
        if (context.flags.is_final) {
            const notificationsEnabled = await this.applicationStateService.getNotificationsEnabled();
            if (notificationsEnabled) {
                this.logger.log('Sending native notification for final message.');
                try {
                    const session = await this.sessionsService.findOne(sessionInput.session_id);
                    const sessionTitle = session?.session_title || 'Task complete';
                    const projectPath = session?.project?.project_path || process.cwd();
                    const relativePath = projectPath.startsWith((0, os_1.homedir)())
                        ? '~' + projectPath.slice((0, os_1.homedir)().length)
                        : projectPath;
                    const port = this.appService.getPort();
                    await this.notificationsService.sendNativeNotification({
                        title: `Repoburg:${port}`,
                        subtitle: sessionTitle,
                        message: relativePath,
                    });
                }
                catch (error) {
                    this.logger.warn('Failed to send notification with session details, falling back to basic notification.');
                    const port = this.appService.getPort();
                    await this.notificationsService.sendNativeNotification({
                        title: `Repoburg:${port}`,
                        message: 'AI finished with a final message.',
                    });
                }
            }
        }
        const syncPromise = this.chatService.getSyncPromise(sessionInput.session_id);
        if (syncPromise) {
            this.logger.log(`Resolving sync promise for sub-agent session ${sessionInput.session_id}`);
            let finalContent = '';
            if (context.flags.is_final && sessionInput.aiActions) {
                const finalAction = sessionInput.aiActions.find((a) => a.action_type === 'final');
                if (finalAction?.plain) {
                    finalContent = finalAction.plain;
                }
            }
            if (!finalContent && sessionInput.raw_llm_response) {
                finalContent = sessionInput.raw_llm_response;
            }
            this.chatService.resolveSyncPromise(sessionInput.session_id, {
                content: finalContent,
                success: true,
                iterations: 0,
                childSessionId: sessionInput.session_id,
            });
        }
    }
};
exports.FrontendNotificationHook = FrontendNotificationHook;
exports.FrontendNotificationHook = FrontendNotificationHook = FrontendNotificationHook_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(5, (0, common_1.Inject)((0, common_1.forwardRef)(() => chat_service_1.ChatService))),
    __metadata("design:paramtypes", [events_gateway_1.EventsGateway,
        application_state_service_1.ApplicationStateService,
        notifications_service_1.NotificationsService,
        sessions_service_1.SessionsService,
        app_service_1.AppService,
        chat_service_1.ChatService])
], FrontendNotificationHook);
//# sourceMappingURL=frontend-notification.hook.js.map