"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.orchestrateRealize = void 0;
const uuid_1 = require("uuid");
const executeCachedBatch_1 = require("../../utils/executeCachedBatch");
const predicateStateMessage_1 = require("../../utils/predicateStateMessage");
const compileRealizeFiles_1 = require("./internal/compileRealizeFiles");
const orchestRateRealizeCorrectCasting_1 = require("./orchestRateRealizeCorrectCasting");
const orchestrateRealizeAuthorization_1 = require("./orchestrateRealizeAuthorization");
const orchestrateRealizeCorrect_1 = require("./orchestrateRealizeCorrect");
const orchestrateRealizeWrite_1 = require("./orchestrateRealizeWrite");
const generateRealizeScenario_1 = require("./utils/generateRealizeScenario");
const orchestrateRealize = (ctx) => (props) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d, _e;
    // PREDICATION
    const operations = (_a = ctx.state().interface) === null || _a === void 0 ? void 0 : _a.document.operations;
    if (!operations)
        throw new Error("Can't do realize agent because operations are nothing.");
    const start = new Date();
    const predicate = (0, predicateStateMessage_1.predicateStateMessage)(ctx.state(), "realize");
    if (predicate !== null)
        return ctx.assistantMessage({
            type: "assistantMessage",
            id: (0, uuid_1.v7)(),
            created_at: start.toISOString(),
            text: predicate,
            completed_at: new Date().toISOString(),
        });
    ctx.dispatch({
        type: "realizeStart",
        id: (0, uuid_1.v7)(),
        created_at: start.toISOString(),
        reason: props.instruction,
        step: (_c = (_b = ctx.state().test) === null || _b === void 0 ? void 0 : _b.step) !== null && _c !== void 0 ? _c : 0,
    });
    // AUTHORIZATIONS
    const authorizations = yield (0, orchestrateRealizeAuthorization_1.orchestrateRealizeAuthorization)(ctx);
    // SCENARIOS
    const scenarios = operations.map((operation) => (0, generateRealizeScenario_1.generateRealizeScenario)(ctx, operation, authorizations));
    const writeProgress = {
        total: scenarios.length,
        completed: 0,
    };
    const writeEvents = yield (0, executeCachedBatch_1.executeCachedBatch)(scenarios.map((scenario) => (promptCacheKey) => __awaiter(void 0, void 0, void 0, function* () {
        var _a;
        const props = {
            totalAuthorizations: authorizations,
            authorization: (_a = scenario.decoratorEvent) !== null && _a !== void 0 ? _a : null,
            scenario,
            progress: writeProgress,
            promptCacheKey,
        };
        const code = yield (0, orchestrateRealizeWrite_1.orchestrateRealizeWrite)(ctx, props).catch(() => {
            return (0, orchestrateRealizeWrite_1.orchestrateRealizeWrite)(ctx, props).catch(() => null);
        });
        return code;
    })));
    const functions = Object.entries(Object.fromEntries(writeEvents
        .filter((w) => w !== null)
        .map((event) => [event.location, event.content]))).map(([location, content]) => {
        const scenario = scenarios.find((el) => el.location === location);
        return {
            location,
            content,
            endpoint: {
                method: scenario.operation.method,
                path: scenario.operation.path,
            },
            name: scenario.functionName,
        };
    });
    const reviewProgress = {
        total: writeEvents.length,
        completed: writeEvents.length,
    };
    const totalCorrected = yield (0, orchestRateRealizeCorrectCasting_1.orchestrateRealizeCorrectCasting)(ctx, authorizations, functions, reviewProgress).then((res) => __awaiter(void 0, void 0, void 0, function* () {
        return (0, orchestrateRealizeCorrect_1.orchestrateRealizeCorrect)(ctx, scenarios, authorizations, res, [], reviewProgress);
    }));
    const compiler = yield ctx.compiler();
    const controllers = yield compiler.realize.controller({
        document: ctx.state().interface.document,
        functions: totalCorrected,
        authorizations,
    });
    const { result } = yield (0, compileRealizeFiles_1.compileRealizeFiles)(ctx, {
        authorizations,
        functions: totalCorrected,
    });
    return ctx.dispatch({
        type: "realizeComplete",
        id: (0, uuid_1.v7)(),
        created_at: new Date().toISOString(),
        functions: totalCorrected,
        authorizations,
        controllers,
        compiled: result,
        step: (_e = (_d = ctx.state().analyze) === null || _d === void 0 ? void 0 : _d.step) !== null && _e !== void 0 ? _e : 0,
        elapsed: new Date().getTime() - start.getTime(),
    });
});
exports.orchestrateRealize = orchestrateRealize;
//# sourceMappingURL=orchestrateRealize.js.map