export class DaemonSurfaceActionHelper {
    context;
    constructor(context) {
        this.context = context;
    }
    buildSurfaceAdapterContext() {
        return {
            serviceRegistry: this.context.serviceRegistry,
            configManager: this.context.configManager,
            routeBindings: this.context.routeBindings,
            sessionBroker: this.context.sessionBroker,
            authorizeSurfaceIngress: (input) => this.authorizeSurfaceIngress(input),
            parseSurfaceControlCommand: (text) => this.parseSurfaceControlCommand(text),
            performSurfaceControlCommand: (command) => this.performSurfaceControlCommand(command),
            performInteractiveSurfaceAction: (actionId, surface, request) => this.performInteractiveSurfaceAction(actionId, surface, request),
            trySpawnAgent: (input, logLabel, sessionId) => this.context.trySpawnAgent(input, logLabel, sessionId),
            queueSurfaceReplyFromBinding: (binding, input) => this.context.queueSurfaceReplyFromBinding(binding, input),
        };
    }
    buildGenericWebhookAdapterContext() {
        return {
            configManager: this.context.configManager,
            routeBindings: this.context.routeBindings,
            sessionBroker: this.context.sessionBroker,
            authorizeSurfaceIngress: (input) => this.authorizeSurfaceIngress(input),
            trySpawnAgent: (input, logLabel, sessionId) => this.context.trySpawnAgent(input, logLabel, sessionId),
            surfaceDeliveryEnabled: (surface) => this.context.surfaceDeliveryEnabled(surface),
            signWebhookPayload: (body, secret) => this.context.signWebhookPayload(body, secret),
            queueWebhookReply: (input) => this.context.queueWebhookReply(input),
        };
    }
    async authorizeSurfaceIngress(input) {
        return this.context.channelPolicy.evaluateIngress(input);
    }
    parseSurfaceControlCommand(text) {
        const trimmed = text.trim();
        const match = trimmed.match(/^(status|cancel|retry)\s+([a-z0-9:_-]+)/i);
        if (!match)
            return null;
        return {
            action: match[1].toLowerCase(),
            id: match[2],
        };
    }
    async performSurfaceControlCommand(command) {
        if (command.action === 'status') {
            const run = this.context.automationManager.getRun(command.id);
            if (run) {
                return `Run ${run.id}: ${run.status}${run.agentId ? ` agent=${run.agentId}` : ''}`;
            }
            const agent = this.context.agentManager.getStatus(command.id);
            if (agent) {
                return `Agent ${agent.id}: ${agent.status}${agent.progress ? ` (${agent.progress})` : ''}`;
            }
            const session = this.context.sessionBroker.getSession(command.id);
            if (session) {
                return `Session ${session.id}: ${session.status} messages=${session.messageCount}${session.activeAgentId ? ` activeAgent=${session.activeAgentId}` : ''}`;
            }
            return `Unknown run, agent, or session: ${command.id}`;
        }
        if (command.action === 'cancel') {
            const run = await this.context.automationManager.cancelRun(command.id, 'surface-cancelled');
            if (run) {
                return `Cancelled run ${run.id}`;
            }
            const agent = this.context.agentManager.getStatus(command.id);
            if (agent) {
                this.context.agentManager.cancel(command.id);
                return `Cancelled agent ${command.id}`;
            }
            return `Unknown run or agent: ${command.id}`;
        }
        try {
            const run = await this.context.automationManager.retryRun(command.id);
            return `Retried run ${run.id}`;
        }
        catch {
            const agent = this.context.agentManager.getStatus(command.id);
            if (agent) {
                const retried = this.context.trySpawnAgent({
                    mode: 'spawn',
                    task: agent.task,
                    ...(agent.model ? { model: agent.model } : {}),
                    ...(agent.provider ? { provider: agent.provider } : {}),
                    ...(agent.tools.length > 0 ? { tools: agent.tools } : {}),
                }, 'DaemonSurfaceActionHelper.performSurfaceControlCommand');
                if (!(retried instanceof Response)) {
                    return `Retried agent ${command.id} as ${retried.id}`;
                }
            }
            return `Unable to retry ${command.id}`;
        }
    }
    async performInteractiveSurfaceAction(actionId, surface, req) {
        const approvalMatch = actionId.match(/^gv:approval:(approve|deny|claim):(.+)$/);
        if (approvalMatch) {
            const [, action, approvalId] = approvalMatch;
            const result = await this.context.handleApprovalAction(approvalId, action, new Request(req.url, {
                method: 'POST',
                headers: req.headers,
            }));
            const body = await result.json().catch(() => ({}));
            return result.ok
                ? `Approval ${action}d: ${approvalId}`
                : String(body.error ?? `Failed to ${action} approval ${approvalId}`);
        }
        const runMatch = actionId.match(/^gv:run:(cancel|retry):(.+)$/);
        if (runMatch) {
            const [, action, runId] = runMatch;
            if (action === 'cancel') {
                const run = await this.context.automationManager.cancelRun(runId, 'interactive-surface-cancel');
                return run ? `Cancelled run ${runId}` : `Failed to cancel run ${runId}`;
            }
            try {
                await this.context.automationManager.retryRun(runId);
                return `Retried run ${runId}`;
            }
            catch (error) {
                return error instanceof Error ? error.message : `Failed to retry run ${runId}`;
            }
        }
        return `No handler for ${surface} action ${actionId}`;
    }
}
