"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.inputToDialogueState = exports.createStateValidator = exports.createSimulator = exports.createConstants = exports.extractConstants = exports.clean = void 0;
const assert_1 = __importDefault(require("assert"));
const js_yaml_1 = __importDefault(require("js-yaml"));
const util_1 = __importDefault(require("util"));
const fs = __importStar(require("fs"));
const thingtalk_1 = require("thingtalk");
const simulation_dialogue_agent_1 = __importDefault(require("../../dialogue-agent/simulator/simulation_dialogue_agent"));
const constants_1 = require("./constants");
Object.defineProperty(exports, "extractConstants", { enumerable: true, get: function () { return constants_1.extractConstants; } });
Object.defineProperty(exports, "createConstants", { enumerable: true, get: function () { return constants_1.createConstants; } });
__exportStar(require("./describe"), exports);
__exportStar(require("./syntax"), exports);
__exportStar(require("./dialogue_state_utils"), exports);
const dialogue_state_utils_1 = require("./dialogue_state_utils");
__exportStar(require("./example-utils"), exports);
// reexport clean from misc-utils
const misc_utils_1 = require("../misc-utils");
Object.defineProperty(exports, "clean", { enumerable: true, get: function () { return misc_utils_1.clean; } });
function validateState(state, forTarget) {
    if (forTarget === 'user') {
        // check that there are no 'proposed' items
        // (should be executed, 'accepted' or 'confirmed')
        for (const item of state.history)
            assert_1.default(item.confirm !== 'proposed');
    }
    else {
        // check that there are no 'confirmed' items that were not executed
        // TODO: if we add "intermediate_context" capabilities to the state machine
        // we can relax this restriction
        for (const item of state.history)
            assert_1.default(item.confirm !== 'confirmed' || item.results !== null);
    }
}
function createSimulator(options) {
    const tpClient = options.thingpediaClient;
    if (!options.schemaRetriever)
        options.schemaRetriever = new thingtalk_1.SchemaRetriever(tpClient, null, true);
    return new simulation_dialogue_agent_1.default(options);
}
exports.createSimulator = createSimulator;
class StateValidator {
    constructor(policyManifest) {
        this._policyManifest = policyManifest;
        this._policy = null;
    }
    async load() {
        if (!this._policyManifest)
            return;
        const buffer = await util_1.default.promisify(fs.readFile)(this._policyManifest, { encoding: 'utf8' });
        const policy = js_yaml_1.default.safeLoad(buffer);
        this._policy = {
            name: policy.name,
            terminalAct: policy.terminalAct,
            dialogueActs: {
                user: new Set(policy.dialogueActs.user),
                agent: new Set(policy.dialogueActs.agent),
                withParam: new Set(policy.dialogueActs.withParam)
            }
        };
    }
    validateUser(state) {
        validateState(state, 'user');
        if (!this._policy)
            return;
        assert_1.default.strictEqual(state.policy, this._policy.name);
        assert_1.default(this._policy.dialogueActs.user.has(state.dialogueAct), `Invalid user dialogue act ${state.dialogueAct}`);
        // if and only if
        assert_1.default((state.dialogueActParam !== null) === (this._policy.dialogueActs.withParam.has(state.dialogueAct)));
    }
    validateAgent(state) {
        validateState(state, 'agent');
        if (!this._policy)
            return;
        assert_1.default.strictEqual(state.policy, this._policy.name);
        assert_1.default(this._policy.dialogueActs.agent.has(state.dialogueAct), `Invalid agent dialogue act ${state.dialogueAct}`);
        // if and only if
        assert_1.default((state.dialogueActParam !== null) === (this._policy.dialogueActs.withParam.has(state.dialogueAct)));
    }
}
function createStateValidator(policyManifest) {
    return new StateValidator(policyManifest);
}
exports.createStateValidator = createStateValidator;
async function inputToDialogueState(policy, context, input) {
    if (input instanceof thingtalk_1.Ast.ControlCommand) {
        if (context === null)
            return null;
        if (input.intent instanceof thingtalk_1.Ast.SpecialControlIntent) {
            switch (input.intent.type) {
                case 'yes':
                case 'no': {
                    const value = new thingtalk_1.Ast.BooleanValue(input.intent.type === 'yes');
                    const handled = await policy.handleAnswer(context, value);
                    if (!handled)
                        return null;
                    return dialogue_state_utils_1.computePrediction(context, handled, 'user');
                }
                default:
                    return null;
            }
        }
        if (input.intent instanceof thingtalk_1.Ast.ChoiceControlIntent)
            return null;
        if (input.intent instanceof thingtalk_1.Ast.AnswerControlIntent) {
            const handled = await policy.handleAnswer(context, input.intent.value);
            if (!handled)
                return null;
            return dialogue_state_utils_1.computePrediction(context, handled, 'user');
        }
        throw new TypeError(`Unrecognized bookkeeping intent`);
    }
    else if (input instanceof thingtalk_1.Ast.Program) {
        // convert thingtalk programs to dialogue states so we can use "\t" without too much typing
        const prediction = new thingtalk_1.Ast.DialogueState(null, 'org.thingpedia.dialogue.transaction', 'execute', null, []);
        for (const stmt of input.statements) {
            if (stmt instanceof thingtalk_1.Ast.Assignment)
                throw new Error(`Unsupported: assignment statement`);
            prediction.history.push(new thingtalk_1.Ast.DialogueHistoryItem(null, stmt, null, 'accepted'));
        }
        return prediction;
    }
    assert_1.default(input instanceof thingtalk_1.Ast.DialogueState);
    return input;
}
exports.inputToDialogueState = inputToDialogueState;
//# sourceMappingURL=index.js.map