"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.proposeStrategyPatch = proposeStrategyPatch;
/**
 * High-level orchestrator that turns a review-agent JSON proposal into a
 * patch landed inside an isolated git worktree. The actual git push +
 * GitHub PR creation lives outside this module — once the worktree is
 * verified, the caller (or an operator) takes over.
 *
 * The five-step pipeline:
 *   1. Render the proposal via phaseHintsRenderer (deterministic YAML).
 *   2. Open a tmp worktree via worktreeRunner (PR3).
 *   3. Apply the rendered entry to the target strategy file.
 *   4. Run a validation hook (typically `validate:strategies`).
 *   5. Return success + the worktree handle, or failure with a structured
 *      reason. Worktree cleanup is the caller's responsibility on success
 *      so they can run heavier downstream checks (regression, e2e) before
 *      pushing the branch.
 *
 * See docs/architecture/self-improving-design.md §13.2 (Worktree isolation), §13 (PR9c).
 */
const path = __importStar(require("path"));
const phaseHintsRenderer_1 = require("./phaseHintsRenderer");
const strategyPatchApplier_1 = require("./strategyPatchApplier");
const worktreeRunner_1 = require("./worktreeRunner");
/**
 * Drive the full pipeline. On success, the worktree is left intact so the
 * caller can run downstream checks; the worktree handle is returned for
 * cleanup. On failure, the worktree is cleaned up (if it was opened) and a
 * structured reason is returned — never throws.
 */
async function proposeStrategyPatch(input) {
    const renderResult = (0, phaseHintsRenderer_1.renderPhaseHint)(input.proposal, { toolRegistry: input.toolRegistry });
    if (!renderResult.ok) {
        return { ok: false, reason: 'render_failed', details: `${renderResult.reason}: ${renderResult.details}` };
    }
    const rendered = renderResult;
    let handle;
    try {
        handle = await (0, worktreeRunner_1.createWorktree)({ jobId: input.jobId, workingDir: input.workingDir });
    }
    catch (err) {
        return {
            ok: false,
            reason: 'worktree_failed',
            details: `failed to create worktree: ${err.message}`,
        };
    }
    const strategyFilePath = path.join(handle.worktreePath, 'backend', 'strategies', `${input.scene}.strategy.md`);
    const apply = (0, strategyPatchApplier_1.applyPhaseHintPatch)(strategyFilePath, rendered.yaml);
    if (!apply.ok) {
        await (0, worktreeRunner_1.removeWorktree)(handle, true);
        return {
            ok: false,
            reason: 'patch_failed',
            details: `${apply.reason}: ${apply.details ?? ''}`,
        };
    }
    if (input.validate) {
        const validation = await input.validate(handle);
        if (!validation.ok) {
            await (0, worktreeRunner_1.removeWorktree)(handle, true);
            return {
                ok: false,
                reason: 'validation_failed',
                details: validation.details ?? 'validation hook returned not-ok',
            };
        }
    }
    return {
        ok: true,
        handle,
        patchFingerprint: rendered.patchFingerprint,
        phaseHintId: rendered.phaseHintId,
        renderedYaml: rendered.yaml,
        strategyFilePath,
    };
}
//# sourceMappingURL=proposeStrategyPatch.js.map