"use strict";
// -*- mode: typescript; indent-tabs-mode: nil; js-basic-offset: 4 -*-
//
// This file is part of Genie
//
// Copyright 2020 The Board of Trustees of the Leland Stanford Junior University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Giovanni Campagna <gcampagn@cs.stanford.edu>
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.impreciseSlotFillAnswer = exports.preciseSlotFillAnswer = exports.makeSlotFillQuestion = void 0;
const assert_1 = __importDefault(require("assert"));
const thingtalk_1 = require("thingtalk");
const C = __importStar(require("../ast_manip"));
const state_manip_1 = require("../state_manip");
function isGoodSlotFillQuestion(ctx, questions) {
    const action = C.getInvocation(ctx.next);
    assert_1.default(action instanceof thingtalk_1.Ast.Invocation);
    for (const q of questions) {
        if (!C.isSameFunction(q.schema, action.schema))
            return false;
        if (q.name === ctx.nextInfo.chainParameter)
            return false;
        const arg = action.schema.getArgument(q.name);
        if (!arg || !arg.is_input)
            return false;
        for (const in_param of action.in_params) {
            if (in_param.name === q.name && !in_param.value.isUndefined)
                return false;
        }
    }
    return true;
}
function useRawModeForSlotFill(arg) {
    // raw mode bypasses _all_ natural language understanding
    // it is used to take in free-form inputs like messages or titles
    const type = arg.type;
    if (!type.isString)
        return false;
    // if the developer specified what to do for the argument, it is authoritative
    const annotation = arg.getAnnotation('raw_mode');
    if (annotation !== undefined)
        return annotation;
    // use raw mode for free-form text parameters
    const stringvalues = arg.getAnnotation('string_values');
    if (!stringvalues)
        return false;
    return ['tt:short_free_text', 'tt:long_free_text'].includes(stringvalues);
}
function makeSlotFillQuestion(ctx, questions) {
    if (!isGoodSlotFillQuestion(ctx, questions))
        return null;
    assert_1.default(questions.length > 0);
    if (questions.length === 1) {
        const action = C.getInvocation(ctx.next);
        const arg = action.schema.getArgument(questions[0].name);
        const type = arg.type;
        const raw = useRawModeForSlotFill(arg);
        return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_slot_fill', questions.map((q) => q.name)), null, type, { raw });
    }
    return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_slot_fill', questions.map((q) => q.name)));
}
exports.makeSlotFillQuestion = makeSlotFillQuestion;
/**
 * Check if the action has parameters for the `questions`
 */
function isSlotFillAnswerValidForQuestion(action, questions) {
    assert_1.default(Array.isArray(questions));
    assert_1.default(action instanceof thingtalk_1.Ast.Invocation);
    return questions.every((question) => {
        for (const in_param of action.in_params) {
            if (in_param.name === question)
                return !in_param.value.isUndefined;
        }
        return false;
    });
}
function preciseSlotFillAnswer(ctx, answer) {
    const questions = ctx.state.dialogueActParam;
    assert_1.default(questions);
    if (!isSlotFillAnswerValidForQuestion(answer, questions))
        return null;
    if (!C.isSameFunction(answer.schema, ctx.nextFunction))
        return null;
    assert_1.default(answer instanceof thingtalk_1.Ast.Invocation);
    assert_1.default(ctx.next && ctx.nextInfo);
    // check that we don't fill the chain parameter through this path:
    // the chain parameter can only be filled if the agent shows the results
    for (const in_param of answer.in_params) {
        if (in_param.name === ctx.nextInfo.chainParameter &&
            !ctx.nextInfo.chainParameterFilled)
            return null;
    }
    const clone = ctx.next.clone();
    clone.confirm = 'accepted';
    clone.results = null;
    const newInvocation = C.getInvocation(clone);
    // modify in place
    state_manip_1.mergeParameters(newInvocation, answer);
    return state_manip_1.addNewItem(ctx, 'execute', null, 'accepted', clone);
}
exports.preciseSlotFillAnswer = preciseSlotFillAnswer;
function impreciseSlotFillAnswer(ctx, answer) {
    const questions = ctx.state.dialogueActParam;
    assert_1.default(Array.isArray(questions));
    if (questions.length !== 1)
        return null;
    let ipslot;
    if (answer instanceof thingtalk_1.Ast.Value) {
        assert_1.default(questions.length === 1);
        const ptype = ctx.nextFunction.getArgType(questions[0]);
        if (!ptype.equals(answer.getType()))
            return null;
        ipslot = {
            schema: ctx.nextFunction,
            ptype: ptype,
            ast: new thingtalk_1.Ast.InputParam(null, questions[0], answer)
        };
    }
    else {
        ipslot = answer;
        if (!questions.some((q) => q === ipslot.ast.name))
            return null;
        if (!C.isSameFunction(answer.schema, ctx.nextFunction))
            return null;
    }
    assert_1.default(ctx.next && ctx.nextInfo);
    if (ipslot.ast.name === ctx.nextInfo.chainParameter)
        return null;
    const clone = ctx.next.clone();
    clone.confirm = 'accepted';
    clone.results = null;
    const newAction = C.getInvocation(clone);
    if (!C.checkInvocationInputParam(ctx.loader, newAction, ipslot))
        return null;
    // modify in place
    state_manip_1.setOrAddInvocationParam(newAction, ipslot.ast.name, ipslot.ast.value);
    return state_manip_1.addNewItem(ctx, 'execute', null, 'accepted', clone);
}
exports.impreciseSlotFillAnswer = impreciseSlotFillAnswer;
//# sourceMappingURL=slot-fill.js.map