"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.orchestrateRealizeCorrect = orchestrateRealizeCorrect;
const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport.js"));
const utils_1 = require("@autobe/utils");
const typia_1 = __importDefault(require("typia"));
const uuid_1 = require("uuid");
const assertSchemaModel_1 = require("../../context/assertSchemaModel");
const executeCachedBatch_1 = require("../../utils/executeCachedBatch");
const transformRealizeCorrectHistories_1 = require("./histories/transformRealizeCorrectHistories");
const compileRealizeFiles_1 = require("./internal/compileRealizeFiles");
const filterDiagnostics_1 = require("./utils/filterDiagnostics");
const getRealizeWriteDto_1 = require("./utils/getRealizeWriteDto");
const replaceImportStatements_1 = require("./utils/replaceImportStatements");
function orchestrateRealizeCorrect(ctx_1, scenarios_1, authorizations_1, functions_1, failures_1, progress_1) {
    return __awaiter(this, arguments, void 0, function* (ctx, scenarios, authorizations, functions, failures, progress, life = ctx.retry) {
        const event = yield (0, compileRealizeFiles_1.compileRealizeFiles)(ctx, {
            authorizations,
            functions,
        });
        if (event.result.type !== "failure")
            return functions;
        else if (life < 0)
            return functions;
        // Extract and process diagnostics
        const diagnostics = event.result.diagnostics;
        if (event.result.diagnostics.every((d) => { var _a; return !((_a = d.file) === null || _a === void 0 ? void 0 : _a.startsWith("src/providers")); })) {
            // No diagnostics related to provider functions, stop correcting
            return functions;
        }
        const locations = Array.from(new Set(diagnostics
            .map((d) => d.file)
            .filter((f) => f !== null)
            .filter((f) => f.startsWith("src/providers"))));
        progress.total += locations.length;
        // Group diagnostics by file and add to failures
        const diagnosticsByFile = {};
        diagnostics.forEach((diagnostic) => {
            const location = diagnostic.file;
            if (location === null)
                return;
            if (!location.startsWith("src/providers"))
                return;
            if (!diagnosticsByFile[location]) {
                const func = functions.find((f) => f.location === location);
                if (!func) {
                    return;
                }
                const failure = {
                    function: func,
                    diagnostics: [],
                };
                diagnosticsByFile[location] = failure;
            }
            diagnosticsByFile[location].diagnostics.push(diagnostic);
        });
        const newFailures = [
            ...failures,
            ...Object.values(diagnosticsByFile),
        ];
        const corrected = yield correct(ctx, locations, scenarios, authorizations, functions, (0, filterDiagnostics_1.filterDiagnostics)(newFailures, functions.map((fn) => fn.location)), progress);
        return orchestrateRealizeCorrect(ctx, scenarios, authorizations, corrected, (0, filterDiagnostics_1.filterDiagnostics)(newFailures, corrected.map((c) => c.location)), progress, life - 1);
    });
}
function correct(ctx, locations, scenarios, authorizations, functions, failures, progress) {
    return __awaiter(this, void 0, void 0, function* () {
        if (locations.length === 0) {
            return functions;
        }
        const corrected = yield (0, executeCachedBatch_1.executeCachedBatch)(locations.map((location) => () => __awaiter(this, void 0, void 0, function* () {
            var _a;
            const scenario = scenarios.find((el) => el.location === location);
            const func = functions.find((el) => el.location === location);
            if (!func) {
                throw new Error("No function found for location: " + location);
            }
            const RealizeFunctionFailures = failures.filter((f) => { var _a; return ((_a = f.function) === null || _a === void 0 ? void 0 : _a.location) === location; });
            if (RealizeFunctionFailures.length && scenario) {
                try {
                    const correctEvent = yield step(ctx, {
                        totalAuthorizations: authorizations,
                        authorization: (_a = scenario.decoratorEvent) !== null && _a !== void 0 ? _a : null,
                        scenario,
                        function: func,
                        failures: RealizeFunctionFailures,
                        progress: progress,
                    });
                    return Object.assign(Object.assign({}, func), { content: correctEvent === null ? "" : correctEvent.content });
                }
                catch (err) {
                    return func;
                }
            }
            return func;
        })));
        // Create a map of corrected functions for efficient lookup
        const correctedMap = new Map(corrected.map((f) => [f.location, f]));
        // Return all functions, with corrected ones replaced
        return functions.map((func) => correctedMap.get(func.location) || func);
    });
}
function step(ctx, props) {
    return __awaiter(this, void 0, void 0, function* () {
        var _a, _b, _c;
        const pointer = {
            value: null,
        };
        const dto = yield (0, getRealizeWriteDto_1.getRealizeWriteDto)(ctx, props.scenario.operation);
        const { tokenUsage } = yield ctx.conversate({
            source: "realizeCorrect",
            controller: createController({
                model: ctx.model,
                build: (next) => {
                    pointer.value = next;
                },
            }),
            histories: (0, transformRealizeCorrectHistories_1.transformRealizeCorrectHistories)({
                state: ctx.state(),
                scenario: props.scenario,
                authorization: props.authorization,
                code: props.function.content,
                dto,
                failures: props.failures.filter((f) => f.function.location === props.function.location),
                totalAuthorizations: props.totalAuthorizations,
            }),
            enforceFunctionCall: true,
            message: utils_1.StringUtil.trim `
      Correct the TypeScript code implementation.
    `,
        });
        if (pointer.value === null) {
            return null;
        }
        pointer.value.revise.final = yield (0, replaceImportStatements_1.replaceImportStatements)(ctx, {
            operation: props.scenario.operation,
            code: pointer.value.revise.final,
            decoratorType: (_a = props.authorization) === null || _a === void 0 ? void 0 : _a.payload.name,
        });
        const event = {
            type: "realizeCorrect",
            id: (0, uuid_1.v7)(),
            location: props.scenario.location,
            content: pointer.value.revise.final,
            tokenUsage,
            completed: ++props.progress.completed,
            total: props.progress.total,
            step: (_c = (_b = ctx.state().analyze) === null || _b === void 0 ? void 0 : _b.step) !== null && _c !== void 0 ? _c : 0,
            created_at: new Date().toISOString(),
        };
        ctx.dispatch(event);
        return event;
    });
}
function createController(props) {
    (0, assertSchemaModel_1.assertSchemaModel)(props.model);
    const application = collection[props.model];
    return {
        protocol: "class",
        name: "Write code",
        application,
        execute: {
            review: (next) => {
                props.build(next);
            },
        },
    };
}
const claude = {
    model: "claude",
    options: {
        reference: true,
        separate: null
    },
    functions: [
        {
            name: "review",
            parameters: {
                description: " Properties containing the multi-phase error correction process\n\n------------------------------\n\nDescription of the current {@link IAutoBeRealizeCorrectApplication.IProps} type:\n\n> Properties for error correction following Chain of Thinking (CoT).\n> \n> All phases are wrapped in a `revise` object for systematic error\n> resolution.",
                type: "object",
                properties: {
                    revise: {
                        description: "Revision process containing all error correction phases.",
                        $ref: "#/$defs/IAutoBeRealizeCorrectApplication.IRevise"
                    }
                },
                required: [
                    "revise"
                ],
                additionalProperties: false,
                $defs: {
                    "IAutoBeRealizeCorrectApplication.IRevise": {
                        type: "object",
                        properties: {
                            errorAnalysis: {
                                description: "Step 1: TypeScript compilation error analysis and resolution strategy.\nAnalyzes TypeScript compiler diagnostics (error codes, messages) to understand\ntype mismatches, missing properties, nullable conflicts, and other compilation issues.",
                                type: "string"
                            },
                            plan: {
                                description: "Step 2: Provider function implementation plan.",
                                type: "string"
                            },
                            prismaSchemas: {
                                description: "Step 3: Relevant Prisma schema definitions.",
                                type: "string"
                            },
                            review: {
                                description: "Step 4: Refined version with improved completeness.",
                                type: "string"
                            },
                            final: {
                                description: "Step 5: Final complete TypeScript function implementation.",
                                type: "string"
                            }
                        },
                        required: [
                            "final"
                        ]
                    }
                }
            },
            description: "Reviews and corrects TypeScript compilation errors.\n\nFixes TypeScript compilation errors while preserving original business\nlogic, applying minimal intervention principle.",
            validate: (() => { const _io0 = input => "object" === typeof input.revise && null !== input.revise && _io1(input.revise); const _io1 = input => (undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis) && (undefined === input.plan || "string" === typeof input.plan) && (undefined === input.prismaSchemas || "string" === typeof input.prismaSchemas) && (undefined === input.review || "string" === typeof input.review) && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => [("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, {
                    path: _path + ".revise",
                    expected: "IAutoBeRealizeCorrectApplication.IRevise",
                    value: input.revise
                })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
                    path: _path + ".revise",
                    expected: "IAutoBeRealizeCorrectApplication.IRevise",
                    value: input.revise
                })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => [undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis || _report(_exceptionable, {
                    path: _path + ".errorAnalysis",
                    expected: "(string | undefined)",
                    value: input.errorAnalysis
                }), undefined === input.plan || "string" === typeof input.plan || _report(_exceptionable, {
                    path: _path + ".plan",
                    expected: "(string | undefined)",
                    value: input.plan
                }), undefined === input.prismaSchemas || "string" === typeof input.prismaSchemas || _report(_exceptionable, {
                    path: _path + ".prismaSchemas",
                    expected: "(string | undefined)",
                    value: input.prismaSchemas
                }), undefined === input.review || "string" === typeof input.review || _report(_exceptionable, {
                    path: _path + ".review",
                    expected: "(string | undefined)",
                    value: input.review
                }), "string" === typeof input.final || _report(_exceptionable, {
                    path: _path + ".final",
                    expected: "string",
                    value: input.final
                })].every(flag => flag); const __is = input => "object" === typeof input && null !== input && _io0(input); let errors; let _report; return input => {
                if (false === __is(input)) {
                    errors = [];
                    _report = __typia_transform__validateReport._validateReport(errors);
                    ((input, _path, _exceptionable = true) => ("object" === typeof input && null !== input || _report(true, {
                        path: _path + "",
                        expected: "IAutoBeRealizeCorrectApplication.IProps",
                        value: input
                    })) && _vo0(input, _path + "", true) || _report(true, {
                        path: _path + "",
                        expected: "IAutoBeRealizeCorrectApplication.IProps",
                        value: input
                    }))(input, "$input", true);
                    const success = 0 === errors.length;
                    return success ? {
                        success,
                        data: input
                    } : {
                        success,
                        errors,
                        data: input
                    };
                }
                return {
                    success: true,
                    data: input
                };
            }; })()
        }
    ]
};
const collection = {
    chatgpt: {
        model: "chatgpt",
        options: {
            reference: true,
            strict: false,
            separate: null
        },
        functions: [
            {
                name: "review",
                parameters: {
                    description: " Properties containing the multi-phase error correction process\n\n------------------------------\n\nDescription of the current {@link IAutoBeRealizeCorrectApplication.IProps} type:\n\n> Properties for error correction following Chain of Thinking (CoT).\n> \n> All phases are wrapped in a `revise` object for systematic error\n> resolution.\n\n### Description of {@link revise} property:\n\n> Revision process containing all error correction phases.",
                    type: "object",
                    properties: {
                        revise: {
                            $ref: "#/$defs/IAutoBeRealizeCorrectApplication.IRevise"
                        }
                    },
                    required: [
                        "revise"
                    ],
                    additionalProperties: false,
                    $defs: {
                        "IAutoBeRealizeCorrectApplication.IRevise": {
                            type: "object",
                            properties: {
                                errorAnalysis: {
                                    description: "Step 1: TypeScript compilation error analysis and resolution strategy.\nAnalyzes TypeScript compiler diagnostics (error codes, messages) to understand\ntype mismatches, missing properties, nullable conflicts, and other compilation issues.",
                                    type: "string"
                                },
                                plan: {
                                    description: "Step 2: Provider function implementation plan.",
                                    type: "string"
                                },
                                prismaSchemas: {
                                    description: "Step 3: Relevant Prisma schema definitions.",
                                    type: "string"
                                },
                                review: {
                                    description: "Step 4: Refined version with improved completeness.",
                                    type: "string"
                                },
                                final: {
                                    description: "Step 5: Final complete TypeScript function implementation.",
                                    type: "string"
                                }
                            },
                            required: [
                                "final"
                            ]
                        }
                    }
                },
                description: "Reviews and corrects TypeScript compilation errors.\n\nFixes TypeScript compilation errors while preserving original business\nlogic, applying minimal intervention principle.",
                validate: (() => { const _io0 = input => "object" === typeof input.revise && null !== input.revise && _io1(input.revise); const _io1 = input => (undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis) && (undefined === input.plan || "string" === typeof input.plan) && (undefined === input.prismaSchemas || "string" === typeof input.prismaSchemas) && (undefined === input.review || "string" === typeof input.review) && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => [("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeRealizeCorrectApplication.IRevise",
                        value: input.revise
                    })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeRealizeCorrectApplication.IRevise",
                        value: input.revise
                    })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => [undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis || _report(_exceptionable, {
                        path: _path + ".errorAnalysis",
                        expected: "(string | undefined)",
                        value: input.errorAnalysis
                    }), undefined === input.plan || "string" === typeof input.plan || _report(_exceptionable, {
                        path: _path + ".plan",
                        expected: "(string | undefined)",
                        value: input.plan
                    }), undefined === input.prismaSchemas || "string" === typeof input.prismaSchemas || _report(_exceptionable, {
                        path: _path + ".prismaSchemas",
                        expected: "(string | undefined)",
                        value: input.prismaSchemas
                    }), undefined === input.review || "string" === typeof input.review || _report(_exceptionable, {
                        path: _path + ".review",
                        expected: "(string | undefined)",
                        value: input.review
                    }), "string" === typeof input.final || _report(_exceptionable, {
                        path: _path + ".final",
                        expected: "string",
                        value: input.final
                    })].every(flag => flag); const __is = input => "object" === typeof input && null !== input && _io0(input); let errors; let _report; return input => {
                    if (false === __is(input)) {
                        errors = [];
                        _report = __typia_transform__validateReport._validateReport(errors);
                        ((input, _path, _exceptionable = true) => ("object" === typeof input && null !== input || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeRealizeCorrectApplication.IProps",
                            value: input
                        })) && _vo0(input, _path + "", true) || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeRealizeCorrectApplication.IProps",
                            value: input
                        }))(input, "$input", true);
                        const success = 0 === errors.length;
                        return success ? {
                            success,
                            data: input
                        } : {
                            success,
                            errors,
                            data: input
                        };
                    }
                    return {
                        success: true,
                        data: input
                    };
                }; })()
            }
        ]
    },
    claude,
    llama: claude,
    deepseek: claude,
    "3.1": claude,
};
//# sourceMappingURL=orchestrateRealizeCorrect.js.map