"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.orchestrateRealizeCorrectCasting = void 0;
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 transformRealizeCorrectCastingHistories_1 = require("./histories/transformRealizeCorrectCastingHistories");
const compileRealizeFiles_1 = require("./internal/compileRealizeFiles");
const orchestrateRealizeCorrectCasting = (ctx_1, authorizations_1, functions_1, progress_1, ...args_1) => __awaiter(void 0, [ctx_1, authorizations_1, functions_1, progress_1, ...args_1], void 0, function* (ctx, authorizations, functions, progress, life = ctx.retry) {
    const validateEvent = yield (0, compileRealizeFiles_1.compileRealizeFiles)(ctx, {
        authorizations,
        functions,
    });
    return predicate(ctx, authorizations, functions, [], progress, validateEvent, life);
});
exports.orchestrateRealizeCorrectCasting = orchestrateRealizeCorrectCasting;
const predicate = (ctx, authorizations, functions, failures, progress, event, life) => __awaiter(void 0, void 0, void 0, function* () {
    if (event.result.type === "failure") {
        ctx.dispatch(event);
        return yield correct(ctx, authorizations, functions, [...failures, ...event.result.diagnostics], progress, event, life);
    }
    return functions;
});
const correct = (ctx, authorizations, functions, failures, progress, event, life) => __awaiter(void 0, void 0, void 0, function* () {
    // Early returns for non-correctable cases
    if (event.result.type !== "failure" || life < 0) {
        return functions;
    }
    const locations = diagnose(event).filter((l) => functions.map((f) => f.location).includes(l));
    // If no locations to correct, return original functions
    if (locations.length === 0) {
        return functions;
    }
    progress.total += locations.length;
    const converted = yield (0, executeCachedBatch_1.executeCachedBatch)(locations.map((location) => () => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b;
        const func = functions.find((f) => f.location === location);
        const pointer = {
            value: null,
        };
        const { tokenUsage } = yield ctx.conversate({
            source: "realizeCorrect",
            histories: (0, transformRealizeCorrectCastingHistories_1.transformRealizeCorrectCastingHistories)([
                {
                    script: func.content,
                    diagnostics: failures.filter((d) => d.file === location),
                },
            ]),
            controller: createController({
                model: ctx.model,
                then: (next) => {
                    pointer.value = next;
                },
                reject: () => {
                    pointer.value = false;
                },
            }),
            enforceFunctionCall: true,
            message: utils_1.StringUtil.trim `
          Fix the TypeScript casting problems to resolve the compilation error.

          Most casting errors are caused by type mismatches between Date types and 
          string & tags.Format<'date-time'>. To fix these:
          - Use ONLY the pre-provided toISOStringSafe() function to convert Date to string
          - Do NOT use .toISOString() method directly (use toISOStringSafe instead)
          - Never use Date type directly in declarations or return values

          You don't need to explain me anything, but just fix or give it up 
          immediately without any hesitation, explanation, and questions.
        `,
        });
        ++progress.completed;
        if (pointer.value === null)
            return { result: "exception", func: func };
        else if (pointer.value === false)
            return { result: "ignore", func: func };
        ctx.dispatch({
            id: (0, uuid_1.v7)(),
            type: "realizeCorrect",
            content: pointer.value.revise.final,
            created_at: new Date().toISOString(),
            location: func.location,
            step: (_b = (_a = ctx.state().analyze) === null || _a === void 0 ? void 0 : _a.step) !== null && _b !== void 0 ? _b : 0,
            tokenUsage,
            completed: progress.completed,
            total: progress.total,
        });
        return {
            result: "success",
            func: Object.assign(Object.assign({}, func), { content: pointer.value.revise.final }),
        };
    })));
    const newValidate = yield (0, compileRealizeFiles_1.compileRealizeFiles)(ctx, {
        authorizations,
        functions: converted.map((c) => c.func),
    });
    const newResult = newValidate.result;
    if (newResult.type === "success") {
        return converted.map((c) => c.func);
    }
    else if (newResult.type === "exception") {
        // Compilation exception, return current functions. because retrying won't help.
        return functions;
    }
    if (newResult.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 converted.map((c) => c.func);
    }
    const newLocations = diagnose(newValidate);
    // Separate successful, failed, and ignored corrections
    const { success, failed, ignored } = separateCorrectionResults(converted, newLocations);
    // If no failures to retry, return success and ignored functions
    if (failed.length === 0) {
        return [...success, ...ignored];
    }
    // Collect diagnostics relevant to failed functions
    const failedLocations = failed.map((f) => f.location);
    const allDiagnostics = [
        ...failures,
        ...(newResult.type === "failure" ? newResult.diagnostics : []),
    ];
    const relevantDiagnostics = filterRelevantDiagnostics(allDiagnostics, failedLocations);
    // Recursively retry failed functions
    const retriedFunctions = yield predicate(ctx, authorizations, failed, relevantDiagnostics, progress, newValidate, life - 1);
    // Get functions that were not modified (not in converted array)
    const convertedLocations = converted.map(c => c.func.location);
    const unchanged = functions.filter(f => !convertedLocations.includes(f.location));
    return [...success, ...ignored, ...retriedFunctions, ...unchanged];
});
/**
 * Extract unique file locations from validation event diagnostics
 *
 * @param event - Validation event containing compilation results
 * @returns Array of unique file paths that have errors
 */
const diagnose = (event) => {
    if (event.result.type !== "failure") {
        return [];
    }
    const diagnostics = event.result.diagnostics;
    const locations = diagnostics
        .map((d) => d.file)
        .filter((f) => f !== null)
        .filter((f) => f.startsWith("src/providers"));
    return Array.from(new Set(locations));
};
/**
 * Separate correction results into successful, failed, and ignored functions
 *
 * @param corrections - Array of correction results
 * @param errorLocations - File paths that still have errors
 * @returns Object with success, failed, and ignored function arrays
 */
const separateCorrectionResults = (corrections, errorLocations) => {
    const success = corrections
        .filter((c) => c.result === "success" && !errorLocations.includes(c.func.location))
        .map((c) => c.func);
    const failed = corrections
        .filter((c) => c.result === "success" && errorLocations.includes(c.func.location))
        .map((c) => c.func);
    const ignored = corrections
        .filter((c) => c.result === "ignore" || c.result === "exception")
        .map((c) => c.func);
    return { success, failed, ignored };
};
/**
 * Filter diagnostics to only include those relevant to specific functions
 *
 * @param diagnostics - All diagnostics
 * @param functionLocations - Locations of functions to filter for
 * @returns Filtered diagnostics
 */
const filterRelevantDiagnostics = (diagnostics, functionLocations) => {
    return diagnostics.filter((d) => d.file && functionLocations.includes(d.file));
};
const createController = (props) => {
    (0, assertSchemaModel_1.assertSchemaModel)(props.model);
    const application = collection[props.model === "chatgpt" ? "chatgpt" : "claude"];
    return {
        protocol: "class",
        name: "correctInvalidRequest",
        application,
        execute: {
            rewrite: (next) => {
                props.then(next);
            },
            reject: () => {
                props.reject();
            },
        },
    };
};
const collection = {
    chatgpt: {
        model: "chatgpt",
        options: {
            reference: true,
            strict: false,
            separate: null
        },
        functions: [
            {
                name: "rewrite",
                parameters: {
                    description: " - The analysis and correction properties\n\n------------------------------\n\nDescription of the current {@link IAutoBeCommonCorrectCastingApplication.IProps} type:\n\n> Properties for the rewrite function containing the type casting error\n> analysis and correction workflow.\n\n### Description of {@link revise} property:\n\n> Review and finalization of type casting corrections.\n> \n> Contains the review of applied corrections and the final code with all\n> type casting issues resolved while preserving type safety and validation intent.",
                    type: "object",
                    properties: {
                        think: {
                            description: "Initial analysis of the type casting or assignment error.\n\nContains the agent's analysis of the specific type mismatch pattern:\n\n- Type of casting error (tag incompatibility, nullable assignment, literal \n  type conversion, etc.)\n- Whether nullable or undefined types are involved\n- If Date to string conversions are needed\n- The chosen fix strategy for the specific error type",
                            type: "string"
                        },
                        draft: {
                            description: "Draft correction with initial type casting fixes.\n\nThe code after applying the first round of fixes:\n\n- Satisfies patterns for tag stripping\n- Date.toISOString() conversions where needed\n- Nullable type narrowing checks\n- Literal type assertions\n- Optional chaining result handling",
                            type: "string"
                        },
                        revise: {
                            $ref: "#/$defs/IAutoBeCommonCorrectCastingApplication.IReviseProps"
                        }
                    },
                    required: [
                        "think",
                        "draft",
                        "revise"
                    ],
                    additionalProperties: false,
                    $defs: {
                        "IAutoBeCommonCorrectCastingApplication.IReviseProps": {
                            description: "Properties for the revision phase of type casting corrections.",
                            type: "object",
                            properties: {
                                review: {
                                    description: "Review of the type casting correction patterns applied.\n\nExplains which correction strategies were used:\n\n- Which satisfies patterns were applied for tag issues\n- Where typia.assert or assertGuard was used\n- How Date conversions were handled\n- What nullable type narrowing was applied\n- How literal type conversions were resolved\n- Confirmation that all type casting issues are resolved",
                                    type: "string"
                                },
                                final: {
                                    description: "Final corrected code with all type casting issues resolved.\n\nThe complete code ready for TypeScript compilation, with all type casting\nand assignment errors properly fixed using appropriate patterns while\nmaintaining type safety and the original validation logic.",
                                    type: "string"
                                }
                            },
                            required: [
                                "review",
                                "final"
                            ]
                        }
                    }
                },
                description: "Rewrite function to fix type casting and assignment errors.\n\nThis function is called when the agent detects any type casting or assignment\nrelated compilation error patterns.\n\nThe agent applies various fix strategies based on the error type:\n\n- **Typia tag incompatibilities**: Uses `satisfies ... as ...` pattern to strip \n  incompatible tags, or `typia.assert<T>()` as a last resort\n- **Date conversions**: Uses `.toISOString()` method for Date to string conversions\n- **Nullable type narrowing**: Applies exhaustive checks (e.g., !== null && !== undefined)\n- **typia.assert vs assertGuard**: Uses assert for value assignment, assertGuard \n  for type narrowing\n- **Literal type conversions**: Uses `typia.assert<T>()` for runtime validation\n- **Optional chaining results**: Uses `=== true` or `??` operators\n- **\"No overlap\" errors**: Removes redundant comparisons",
                validate: (() => { const _io0 = input => "string" === typeof input.think && "string" === typeof input.draft && ("object" === typeof input.revise && null !== input.revise && _io1(input.revise)); const _io1 = input => "string" === typeof input.review && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.think || _report(_exceptionable, {
                        path: _path + ".think",
                        expected: "string",
                        value: input.think
                    }), "string" === typeof input.draft || _report(_exceptionable, {
                        path: _path + ".draft",
                        expected: "string",
                        value: input.draft
                    }), ("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps",
                        value: input.revise
                    })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps",
                        value: input.revise
                    })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => ["string" === typeof input.review || _report(_exceptionable, {
                        path: _path + ".review",
                        expected: "string",
                        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: "IAutoBeCommonCorrectCastingApplication.IProps",
                            value: input
                        })) && _vo0(input, _path + "", true) || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeCommonCorrectCastingApplication.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
                    };
                }; })()
            },
            {
                name: "reject",
                parameters: {
                    type: "object",
                    properties: {},
                    additionalProperties: false,
                    required: [],
                    $defs: {}
                },
                description: "Reject function when error is not related to type casting or assignment.\n\nThis function is called when the compilation error is unrelated to type \ncasting issues (e.g., missing imports, syntax errors, undefined variables), \nindicating the error should be handled by a different agent.",
                validate: (() => { const __is = input => true; let errors; let _report; return input => {
                    if (false === __is(input)) {
                        errors = [];
                        _report = __typia_transform__validateReport._validateReport(errors);
                        ((input, _path, _exceptionable = true) => true)(input, "$input", true);
                        const success = 0 === errors.length;
                        return success ? {
                            success,
                            data: input
                        } : {
                            success,
                            errors,
                            data: input
                        };
                    }
                    return {
                        success: true,
                        data: input
                    };
                }; })()
            }
        ]
    },
    claude: {
        model: "claude",
        options: {
            reference: true,
            separate: null
        },
        functions: [
            {
                name: "rewrite",
                parameters: {
                    description: " - The analysis and correction properties\n\n------------------------------\n\nDescription of the current {@link IAutoBeCommonCorrectCastingApplication.IProps} type:\n\n> Properties for the rewrite function containing the type casting error\n> analysis and correction workflow.",
                    type: "object",
                    properties: {
                        think: {
                            description: "Initial analysis of the type casting or assignment error.\n\nContains the agent's analysis of the specific type mismatch pattern:\n\n- Type of casting error (tag incompatibility, nullable assignment, literal \n  type conversion, etc.)\n- Whether nullable or undefined types are involved\n- If Date to string conversions are needed\n- The chosen fix strategy for the specific error type",
                            type: "string"
                        },
                        draft: {
                            description: "Draft correction with initial type casting fixes.\n\nThe code after applying the first round of fixes:\n\n- Satisfies patterns for tag stripping\n- Date.toISOString() conversions where needed\n- Nullable type narrowing checks\n- Literal type assertions\n- Optional chaining result handling",
                            type: "string"
                        },
                        revise: {
                            description: "Review and finalization of type casting corrections.\n\nContains the review of applied corrections and the final code with all\ntype casting issues resolved while preserving type safety and validation intent.",
                            $ref: "#/$defs/IAutoBeCommonCorrectCastingApplication.IReviseProps"
                        }
                    },
                    required: [
                        "think",
                        "draft",
                        "revise"
                    ],
                    additionalProperties: false,
                    $defs: {
                        "IAutoBeCommonCorrectCastingApplication.IReviseProps": {
                            description: "Properties for the revision phase of type casting corrections.",
                            type: "object",
                            properties: {
                                review: {
                                    description: "Review of the type casting correction patterns applied.\n\nExplains which correction strategies were used:\n\n- Which satisfies patterns were applied for tag issues\n- Where typia.assert or assertGuard was used\n- How Date conversions were handled\n- What nullable type narrowing was applied\n- How literal type conversions were resolved\n- Confirmation that all type casting issues are resolved",
                                    type: "string"
                                },
                                final: {
                                    description: "Final corrected code with all type casting issues resolved.\n\nThe complete code ready for TypeScript compilation, with all type casting\nand assignment errors properly fixed using appropriate patterns while\nmaintaining type safety and the original validation logic.",
                                    type: "string"
                                }
                            },
                            required: [
                                "review",
                                "final"
                            ]
                        }
                    }
                },
                description: "Rewrite function to fix type casting and assignment errors.\n\nThis function is called when the agent detects any type casting or assignment\nrelated compilation error patterns.\n\nThe agent applies various fix strategies based on the error type:\n\n- **Typia tag incompatibilities**: Uses `satisfies ... as ...` pattern to strip \n  incompatible tags, or `typia.assert<T>()` as a last resort\n- **Date conversions**: Uses `.toISOString()` method for Date to string conversions\n- **Nullable type narrowing**: Applies exhaustive checks (e.g., !== null && !== undefined)\n- **typia.assert vs assertGuard**: Uses assert for value assignment, assertGuard \n  for type narrowing\n- **Literal type conversions**: Uses `typia.assert<T>()` for runtime validation\n- **Optional chaining results**: Uses `=== true` or `??` operators\n- **\"No overlap\" errors**: Removes redundant comparisons",
                validate: (() => { const _io0 = input => "string" === typeof input.think && "string" === typeof input.draft && ("object" === typeof input.revise && null !== input.revise && _io1(input.revise)); const _io1 = input => "string" === typeof input.review && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.think || _report(_exceptionable, {
                        path: _path + ".think",
                        expected: "string",
                        value: input.think
                    }), "string" === typeof input.draft || _report(_exceptionable, {
                        path: _path + ".draft",
                        expected: "string",
                        value: input.draft
                    }), ("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps",
                        value: input.revise
                    })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps",
                        value: input.revise
                    })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => ["string" === typeof input.review || _report(_exceptionable, {
                        path: _path + ".review",
                        expected: "string",
                        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: "IAutoBeCommonCorrectCastingApplication.IProps",
                            value: input
                        })) && _vo0(input, _path + "", true) || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeCommonCorrectCastingApplication.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
                    };
                }; })()
            },
            {
                name: "reject",
                parameters: {
                    type: "object",
                    properties: {},
                    additionalProperties: false,
                    required: [],
                    $defs: {}
                },
                description: "Reject function when error is not related to type casting or assignment.\n\nThis function is called when the compilation error is unrelated to type \ncasting issues (e.g., missing imports, syntax errors, undefined variables), \nindicating the error should be handled by a different agent.",
                validate: (() => { const __is = input => true; let errors; let _report; return input => {
                    if (false === __is(input)) {
                        errors = [];
                        _report = __typia_transform__validateReport._validateReport(errors);
                        ((input, _path, _exceptionable = true) => true)(input, "$input", true);
                        const success = 0 === errors.length;
                        return success ? {
                            success,
                            data: input
                        } : {
                            success,
                            errors,
                            data: input
                        };
                    }
                    return {
                        success: true,
                        data: input
                    };
                }; })()
            }
        ]
    },
};
//# sourceMappingURL=orchestRateRealizeCorrectCasting.js.map