"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.orchestrateRealizeWrite = orchestrateRealizeWrite;
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 transformRealizeWriteHistories_1 = require("./histories/transformRealizeWriteHistories");
const getRealizeWriteDto_1 = require("./utils/getRealizeWriteDto");
const replaceImportStatements_1 = require("./utils/replaceImportStatements");
function orchestrateRealizeWrite(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: "realizeWrite",
            histories: (0, transformRealizeWriteHistories_1.transformRealizeWriteHistories)({
                state: ctx.state(),
                scenario: props.scenario,
                authorization: props.authorization,
                totalAuthorizations: props.totalAuthorizations,
                dto,
            }),
            controller: createController({
                model: ctx.model,
                build: (next) => {
                    pointer.value = next;
                },
            }),
            enforceFunctionCall: true,
            promptCacheKey: props.promptCacheKey,
            message: utils_1.StringUtil.trim `
      Write complete, production-ready TypeScript code that strictly follows these rules:

      DO NOT:
      - Use the native \`Date\` type anywhere
      - Use \`as\` for type assertions

      DO:
      - Write all date/datetime values as \`string & tags.Format<'date-time'>\`
      - Generate UUIDs using \`v4()\` and type as \`string & tags.Format<'uuid'>\`
      - Resolve types properly without assertions
      - Type all functions with clear parameter and return types
      6. Do not skip validations or default values where necessary.
      7. Follow functional, immutable, and consistent code structure.

      Use \`@nestia/e2e\` test structure if relevant.
    `,
        });
        if (pointer.value === null)
            throw new Error("Failed to write code.");
        pointer.value.final = yield (0, replaceImportStatements_1.replaceImportStatements)(ctx, {
            operation: props.scenario.operation,
            code: pointer.value.final,
            decoratorType: (_a = props.authorization) === null || _a === void 0 ? void 0 : _a.payload.name,
        });
        const event = {
            type: "realizeWrite",
            id: (0, uuid_1.v7)(),
            location: props.scenario.location,
            content: pointer.value.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: {
            coding: (next) => {
                props.build(next);
            },
        },
    };
}
const claude = {
    model: "claude",
    options: {
        reference: true,
        separate: null
    },
    functions: [
        {
            name: "coding",
            parameters: {
                description: " Properties containing the multi-phase implementation plan and\ncode\n\n------------------------------\n\nDescription of the current {@link IAutoBeRealizeWriteApplication.IProps} type:\n\n> Properties for the Realize Write Application following Chain of Thinking\n> (CoT).\n> \n> Each field represents a distinct phase in the implementation process.\n> Detailed guidelines are in REALIZE_WRITE.md.",
                type: "object",
                properties: {
                    plan: {
                        description: "Step 1 - Planning Phase (CoT: Initial Reasoning)\n\nStrategic plan following SCHEMA-FIRST APPROACH:\n\n1. Verify Prisma schema fields (list existing and non-existing)\n2. Plan field usage in operations\n3. Plan type conversions and nullable handling\n4. Define implementation approach with error handling\n\nSee REALIZE_WRITE.md for detailed requirements.",
                        type: "string"
                    },
                    prismaSchemas: {
                        description: "Step 2 - Relevant Prisma schema models and fields",
                        type: "string"
                    },
                    review: {
                        description: "Step 3 - Refined version with real operations",
                        type: "string"
                    },
                    final: {
                        description: "Step 4 - Final implementation See REALIZE_WRITE.md for requirements",
                        type: "string"
                    }
                },
                required: [
                    "plan",
                    "prismaSchemas",
                    "review",
                    "final"
                ],
                additionalProperties: false,
                $defs: {}
            },
            description: "Generates provider function implementation through multi-phase development.\n\nThis method implements a systematic approach to generate NestJS provider\nfunctions that handle business logic for API operations. It follows a\nschema-first approach with multiple refinement phases to ensure type-safe,\nerror-free code generation.\n\nThe generation process includes:\n\n1. Strategic planning based on Prisma schema analysis\n2. Schema definition for relevant models\n3. Review and refinement for completeness\n4. Final implementation with all validations and type safety",
            validate: (() => { const _io0 = input => "string" === typeof input.plan && "string" === typeof input.prismaSchemas && "string" === typeof input.review && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.plan || _report(_exceptionable, {
                    path: _path + ".plan",
                    expected: "string",
                    value: input.plan
                }), "string" === typeof input.prismaSchemas || _report(_exceptionable, {
                    path: _path + ".prismaSchemas",
                    expected: "string",
                    value: input.prismaSchemas
                }), "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: "IAutoBeRealizeWriteApplication.IProps",
                        value: input
                    })) && _vo0(input, _path + "", true) || _report(true, {
                        path: _path + "",
                        expected: "IAutoBeRealizeWriteApplication.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: "coding",
                parameters: {
                    description: " Properties containing the multi-phase implementation plan and\ncode\n\n------------------------------\n\nDescription of the current {@link IAutoBeRealizeWriteApplication.IProps} type:\n\n> Properties for the Realize Write Application following Chain of Thinking\n> (CoT).\n> \n> Each field represents a distinct phase in the implementation process.\n> Detailed guidelines are in REALIZE_WRITE.md.",
                    type: "object",
                    properties: {
                        plan: {
                            description: "Step 1 - Planning Phase (CoT: Initial Reasoning)\n\nStrategic plan following SCHEMA-FIRST APPROACH:\n\n1. Verify Prisma schema fields (list existing and non-existing)\n2. Plan field usage in operations\n3. Plan type conversions and nullable handling\n4. Define implementation approach with error handling\n\nSee REALIZE_WRITE.md for detailed requirements.",
                            type: "string"
                        },
                        prismaSchemas: {
                            description: "Step 2 - Relevant Prisma schema models and fields",
                            type: "string"
                        },
                        review: {
                            description: "Step 3 - Refined version with real operations",
                            type: "string"
                        },
                        final: {
                            description: "Step 4 - Final implementation See REALIZE_WRITE.md for requirements",
                            type: "string"
                        }
                    },
                    required: [
                        "plan",
                        "prismaSchemas",
                        "review",
                        "final"
                    ],
                    additionalProperties: false,
                    $defs: {}
                },
                description: "Generates provider function implementation through multi-phase development.\n\nThis method implements a systematic approach to generate NestJS provider\nfunctions that handle business logic for API operations. It follows a\nschema-first approach with multiple refinement phases to ensure type-safe,\nerror-free code generation.\n\nThe generation process includes:\n\n1. Strategic planning based on Prisma schema analysis\n2. Schema definition for relevant models\n3. Review and refinement for completeness\n4. Final implementation with all validations and type safety",
                validate: (() => { const _io0 = input => "string" === typeof input.plan && "string" === typeof input.prismaSchemas && "string" === typeof input.review && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.plan || _report(_exceptionable, {
                        path: _path + ".plan",
                        expected: "string",
                        value: input.plan
                    }), "string" === typeof input.prismaSchemas || _report(_exceptionable, {
                        path: _path + ".prismaSchemas",
                        expected: "string",
                        value: input.prismaSchemas
                    }), "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: "IAutoBeRealizeWriteApplication.IProps",
                            value: input
                        })) && _vo0(input, _path + "", true) || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeRealizeWriteApplication.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=orchestrateRealizeWrite.js.map