"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 });
const assert_1 = __importDefault(require("assert"));
const thingtalk_1 = require("thingtalk");
const value_category_1 = __importDefault(require("./value-category"));
const I18n = __importStar(require("../i18n"));
const generator_1 = __importDefault(require("../sentence-generator/generator"));
const ThingTalkUtils = __importStar(require("../utils/thingtalk"));
const MAX_DEPTH = 7;
const TARGET_PRUNING_SIZES = [50, 100];
let TEMPLATE_FILE_PATH;
try {
    // try the path relative to our build location first (in dist/lib/dialogue-agent)
    TEMPLATE_FILE_PATH = require.resolve('../../../languages-dist/thingtalk/en/dialogue.genie');
}
catch (e) {
    if (e.code !== 'MODULE_NOT_FOUND')
        throw e;
    try {
        // if that fails, try the location relative to our source directory
        // (in case we're running with ts-node)
        TEMPLATE_FILE_PATH = require.resolve('../../languages-dist/thingtalk/en/dialogue.genie');
    }
    catch (e) {
        if (e.code !== 'MODULE_NOT_FOUND')
            throw e;
        // if that still fails, we're probably in the "compile-template" call
        // in a clean build, so set ourselves empty (it will not matter)
        TEMPLATE_FILE_PATH = '';
    }
}
function arrayEqual(a, b) {
    if (a.length !== b.length)
        return false;
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i])
            return false;
    }
    return true;
}
class DialoguePolicy {
    constructor(options) {
        this._thingpedia = options.thingpedia;
        this._schemas = options.schemas;
        this._locale = options.locale;
        this._timezone = options.timezone;
        this._langPack = I18n.get(options.locale);
        this._entityAllocator = new thingtalk_1.Syntax.SequentialEntityAllocator({});
        this._rng = options.rng;
        assert_1.default(this._rng);
        this._debug = options.debug;
        this._sentenceGenerator = null;
        this._generatorDevices = null;
        this._generatorOptions = undefined;
    }
    async _initializeGenerator(forDevices) {
        console.log('Initializing dialogue policy for devices: ' + forDevices.join(', '));
        this._generatorOptions = {
            contextual: true,
            rootSymbol: '$agent',
            forSide: 'agent',
            flags: {
                // FIXME
                dialogues: true,
                inference: true,
            },
            rng: this._rng,
            locale: this._locale,
            timezone: this._timezone,
            templateFiles: [TEMPLATE_FILE_PATH],
            thingpediaClient: this._thingpedia,
            schemaRetriever: this._schemas,
            entityAllocator: this._entityAllocator,
            onlyDevices: forDevices,
            maxDepth: MAX_DEPTH,
            maxConstants: 5,
            targetPruningSize: TARGET_PRUNING_SIZES[0],
            debug: this._debug ? 2 : 1,
            contextInitializer: (state, functionTable, contextTable) => {
                // ask the target language to extract the constants from the context
                this._entityAllocator.reset();
                if (state !== null) {
                    const constants = ThingTalkUtils.extractConstants(state, this._entityAllocator);
                    sentenceGenerator.addConstantsFromContext(constants);
                }
                return functionTable.context(state, contextTable);
            }
        };
        const sentenceGenerator = new generator_1.default(this._generatorOptions);
        this._sentenceGenerator = sentenceGenerator;
        this._generatorDevices = forDevices;
        await this._sentenceGenerator.initialize();
    }
    _extractDevices(state) {
        if (state === null)
            return [];
        const devices = new Set();
        state.visit(new class extends thingtalk_1.Ast.NodeVisitor {
            visitDeviceSelector(selector) {
                devices.add(selector.kind);
                return true;
            }
        });
        const deviceArray = Array.from(devices);
        deviceArray.sort();
        return deviceArray;
    }
    async _ensureGeneratorForState(state) {
        const devices = this._extractDevices(state);
        if (this._generatorDevices && arrayEqual(this._generatorDevices, devices))
            return;
        await this._initializeGenerator(devices);
    }
    async handleAnswer(state, value) {
        if (state === null)
            return null;
        await this._ensureGeneratorForState(state);
        return this._sentenceGenerator.invokeFunction('answer', state, value, this._sentenceGenerator.contextTable);
    }
    _generateDerivation(state) {
        let derivation;
        // try with a low pruning size first, because that's faster, and then increase
        // the pruning size if we don't find anything useful
        for (const pruningSize of TARGET_PRUNING_SIZES) {
            this._generatorOptions.targetPruningSize = pruningSize;
            derivation = this._sentenceGenerator.generateOne(state);
            if (derivation !== undefined)
                break;
        }
        return derivation;
    }
    async chooseAction(state) {
        await this._ensureGeneratorForState(state);
        const derivation = this._generateDerivation(state);
        if (derivation === undefined)
            return derivation;
        let sentence = derivation.toString();
        sentence = this._langPack.postprocessSynthetic(sentence, derivation.value.state, this._rng, 'agent');
        let expect;
        if (derivation.value.end)
            expect = null;
        else if (derivation.value.expect)
            expect = value_category_1.default.fromType(derivation.value.expect);
        else
            expect = value_category_1.default.Command;
        if (expect === value_category_1.default.RawString && !derivation.value.raw)
            expect = value_category_1.default.Command;
        return [derivation.value.state, expect, sentence, this._entityAllocator.entities, derivation.value.numResults];
    }
}
exports.default = DialoguePolicy;
//# sourceMappingURL=dialogue_policy.js.map