/**
 * AskAgentQuestionUseCase
 *
 * Persists a new {@link AgentQuestion} and, for blocking-kind questions,
 * registers an in-process awaiter so the caller (typically the SDK V2
 * `canUseTool` callback) can `await` until {@link AnswerAgentQuestionUseCase}
 * settles it.
 *
 * After persistence, the question is forwarded to the
 * {@link AgentQuestionSupervisorRouter} (spec 093, task 31). The router
 * is a no-op when the question's `answerer` is `user`, when the
 * question is gate-linked (the worker handles the gate path), or when
 * no {@link SupervisorPolicy} is configured for the scope. In
 * autonomous mode the router may settle the question via
 * {@link AnswerAgentQuestionUseCase} before this method returns,
 * which resolves the awaiter for blocking questions in the same tick.
 *
 * Feature-flag short-circuit: with `featureFlags.collaboration` off, the
 * use case returns `{ enabled: false }` without persisting or registering
 * anything (NFR-14 byte-identical default).
 */
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); }
};
import { inject, injectable } from 'tsyringe';
import { randomUUID } from 'node:crypto';
import { AgentQuestionSupervisorRouter } from './agent-question-supervisor-router.js';
import { EscalateToUserUseCase } from './escalate-to-user.use-case.js';
import { AgentQuestionKind, AgentQuestionStatus, NotificationEventType, NotificationSeverity, } from '../../../domain/generated/output.js';
let AskAgentQuestionUseCase = class AskAgentQuestionUseCase {
    questionRepository;
    deferredRegistry;
    settings;
    supervisorRouter;
    escalateToUser;
    constructor(questionRepository, deferredRegistry, settings, supervisorRouter, escalateToUser) {
        this.questionRepository = questionRepository;
        this.deferredRegistry = deferredRegistry;
        this.settings = settings;
        this.supervisorRouter = supervisorRouter;
        this.escalateToUser = escalateToUser;
    }
    async execute(input) {
        const flagOn = await this.isCollaborationEnabled();
        if (!flagOn)
            return { enabled: false };
        const now = new Date();
        const question = {
            id: randomUUID(),
            appId: input.appId,
            featureId: input.featureId,
            agentRunId: input.agentRunId,
            kind: input.kind,
            prompt: input.prompt,
            optionsJson: input.options && input.options.length > 0 ? JSON.stringify(input.options) : undefined,
            defaultAnswer: input.defaultAnswer,
            answerer: input.answerer,
            status: AgentQuestionStatus.pending,
            answer: undefined,
            answeredBy: undefined,
            answeredAt: undefined,
            expiresAt: input.expiresAt,
            createdAt: now,
            updatedAt: now,
        };
        await this.questionRepository.create(question);
        const result = { enabled: true, question };
        if (input.kind === AgentQuestionKind.blocking) {
            const timeoutMs = input.expiresAt instanceof Date
                ? Math.max(input.expiresAt.getTime() - now.getTime(), 1)
                : undefined;
            result.awaiter = this.deferredRegistry.register(question.id, {
                appId: input.appId,
                featureId: input.featureId,
                agentRunId: input.agentRunId,
            }, timeoutMs);
        }
        // Route through the supervisor (spec 093, task 31). For non-gate
        // questions with answerer ∈ {supervisor, either} and a configured
        // policy, the supervisor evaluates the question. In autonomous
        // mode the router may answer the question before this method
        // returns, which resolves the awaiter for blocking questions in
        // the same tick.
        await this.supervisorRouter.routeIfApplicable(question);
        // Surface the question to the user via the existing notification
        // surface (spec 093, task 34). Three-tier urgency maps to the new
        // NotificationEventType values: blocking interrupts, question goes
        // to the inbox, info skips notification entirely (activity feed
        // only — research decision 11).
        if (question.kind !== AgentQuestionKind.info) {
            const isBlocking = question.kind === AgentQuestionKind.blocking;
            await this.escalateToUser.execute({
                eventType: isBlocking
                    ? NotificationEventType.AgentQuestionBlocking
                    : NotificationEventType.AgentQuestionPending,
                severity: isBlocking ? NotificationSeverity.Warning : NotificationSeverity.Info,
                message: question.prompt,
                agentRunId: question.agentRunId,
                featureId: question.featureId ?? '',
                featureName: question.featureId ?? '',
                sourceEventId: question.id,
                actorId: 'agent',
                auditField: `agent.question.${question.kind}`,
                timestamp: now,
            });
        }
        return result;
    }
    async isCollaborationEnabled() {
        const settings = await this.settings.load();
        return settings?.featureFlags?.collaboration === true;
    }
};
AskAgentQuestionUseCase = __decorate([
    injectable(),
    __param(0, inject('IAgentQuestionRepository')),
    __param(1, inject('IDeferredQuestionRegistry')),
    __param(2, inject('ISettingsRepository')),
    __param(3, inject(AgentQuestionSupervisorRouter)),
    __param(4, inject(EscalateToUserUseCase)),
    __metadata("design:paramtypes", [Object, Object, Object, AgentQuestionSupervisorRouter,
        EscalateToUserUseCase])
], AskAgentQuestionUseCase);
export { AskAgentQuestionUseCase };
