"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.inferResolveIORunnerEvidenceContentType = inferResolveIORunnerEvidenceContentType;
exports.buildResolveIORunnerEvidenceCid = buildResolveIORunnerEvidenceCid;
exports.inferResolveIORunnerEvidenceCaption = inferResolveIORunnerEvidenceCaption;
exports.normalizeResolveIORunnerPersistedEvidenceFiles = normalizeResolveIORunnerPersistedEvidenceFiles;
exports.mergeResolveIORunnerEvidenceFileIds = mergeResolveIORunnerEvidenceFileIds;
exports.collectResolveIORunnerEvidenceArtifactFilesFromRoots = collectResolveIORunnerEvidenceArtifactFilesFromRoots;
exports.toResolveIORunnerEvidenceAttachmentsFromRoots = toResolveIORunnerEvidenceAttachmentsFromRoots;
exports.collectResolveIORunnerEvidenceArtifactPaths = collectResolveIORunnerEvidenceArtifactPaths;
exports.toResolveIORunnerEvidenceAttachments = toResolveIORunnerEvidenceAttachments;
exports.persistResolveIORunnerEvidenceArtifacts = persistResolveIORunnerEvidenceArtifacts;
var node_crypto_1 = require("node:crypto");
var fs = require("fs");
var path = require("path");
function inferResolveIORunnerEvidenceContentType(fileName) {
    var normalized = String(fileName || '').trim().toLowerCase();
    if (normalized.endsWith('.png')) {
        return 'image/png';
    }
    if (normalized.endsWith('.jpg') || normalized.endsWith('.jpeg')) {
        return 'image/jpeg';
    }
    if (normalized.endsWith('.webp')) {
        return 'image/webp';
    }
    if (normalized.endsWith('.zip')) {
        return 'application/zip';
    }
    if (normalized.endsWith('.json')) {
        return 'application/json';
    }
    if (normalized.endsWith('.txt') || normalized.endsWith('.log')) {
        return 'text/plain; charset=utf-8';
    }
    return 'application/octet-stream';
}
function buildResolveIORunnerEvidenceCid(filePath) {
    var baseName = path.basename(String(filePath || '').trim()) || 'runner-artifact';
    var normalized = baseName
        .toLowerCase()
        .replace(/[^a-z0-9._-]+/g, '-')
        .replace(/^-+|-+$/g, '')
        .slice(0, 80) || 'runner-artifact';
    var digest = (0, node_crypto_1.createHash)('sha1').update(String(filePath || '')).digest('hex').slice(0, 12);
    return "".concat(normalized, "-").concat(digest, "@resolveio-runner");
}
function inferResolveIORunnerEvidenceCaption(fileNameOrPath) {
    var baseName = path.basename(String(fileNameOrPath || '').trim()).replace(/\.[a-z0-9]+$/i, '');
    var normalized = baseName
        .toLowerCase()
        .replace(/[_-]+/g, ' ')
        .replace(/\b\d{4,}\b/g, '')
        .replace(/\s+/g, ' ')
        .trim();
    if (!normalized) {
        return 'QA screenshot captured during validation.';
    }
    if (/\bbefore\b/.test(normalized)) {
        return 'Before: the tested page is loaded at the start of the workflow.';
    }
    if (/\bready\b/.test(normalized) && /\bimport\b/.test(normalized)) {
        return 'Ready to import: the uploaded data was accepted and is displayed for review before submission.';
    }
    if (/\bsubmitted\b|\bresult\b|\bafter\b|\bcomplete\b|\bsuccess\b|\bverified\b/.test(normalized)) {
        return 'After submission: the workflow completed and the result confirms the change worked.';
    }
    if (/\bdialog\b|\bmodal\b|\bpopup\b/.test(normalized)) {
        return 'Dialog: the tested prompt or modal is shown in the expected state.';
    }
    if (/\bmobile\b/.test(normalized)) {
        return 'Mobile view: the tested workflow is shown at the mobile viewport.';
    }
    if (/\bdesktop\b|\bwide\b/.test(normalized)) {
        return 'Desktop view: the tested workflow is shown at a full-width desktop viewport.';
    }
    return baseName
        .replace(/[_-]+/g, ' ')
        .replace(/\b\w/g, function (letter) { return letter.toUpperCase(); })
        .slice(0, 180);
}
function normalizeResolveIORunnerPersistedEvidenceFiles(value) {
    if (!Array.isArray(value)) {
        return [];
    }
    return value
        .map(function (item) {
        var fileId = String((item === null || item === void 0 ? void 0 : item.file_id) || (item === null || item === void 0 ? void 0 : item.id_file) || (item === null || item === void 0 ? void 0 : item._id) || '').trim();
        if (!fileId) {
            return null;
        }
        return {
            file_id: fileId,
            filename: String((item === null || item === void 0 ? void 0 : item.filename) || (item === null || item === void 0 ? void 0 : item.name) || '').trim(),
            key: String((item === null || item === void 0 ? void 0 : item.key) || '').trim() || undefined,
            contentType: String((item === null || item === void 0 ? void 0 : item.contentType) || (item === null || item === void 0 ? void 0 : item.content_type) || '').trim() || undefined,
            caption: String((item === null || item === void 0 ? void 0 : item.caption) || '').trim() || undefined,
            content_hash: String((item === null || item === void 0 ? void 0 : item.content_hash) || (item === null || item === void 0 ? void 0 : item.hash) || '').trim() || undefined,
            ticket_url: String((item === null || item === void 0 ? void 0 : item.ticket_url) || '').trim() || undefined
        };
    })
        .filter(function (item) { return !!item; });
}
function mergeResolveIORunnerEvidenceFileIds() {
    var values = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        values[_i] = arguments[_i];
    }
    var ids = [];
    var seen = new Set();
    var push = function (value) {
        if (Array.isArray(value)) {
            value.forEach(push);
            return;
        }
        var id = String((value === null || value === void 0 ? void 0 : value.file_id) || (value === null || value === void 0 ? void 0 : value.id_file) || (value === null || value === void 0 ? void 0 : value._id) || value || '').trim();
        if (!id || seen.has(id)) {
            return;
        }
        seen.add(id);
        ids.push(id);
    };
    values.forEach(push);
    return ids;
}
function collectResolveIORunnerEvidenceText(value, output) {
    if (value === null || value === undefined) {
        return;
    }
    if (typeof value === 'string') {
        output.push(value);
        return;
    }
    if (Array.isArray(value)) {
        value.forEach(function (entry) { return collectResolveIORunnerEvidenceText(entry, output); });
        return;
    }
    if (typeof value === 'object') {
        Object.values(value).forEach(function (entry) { return collectResolveIORunnerEvidenceText(entry, output); });
    }
}
function normalizeArtifactCandidatePath(value) {
    return String(value || '')
        .trim()
        .replace(/[),.;:'"]+$/g, '')
        .replace(/\\/g, '/');
}
function pathExists(filePath) {
    try {
        return !!filePath && fs.existsSync(filePath) && fs.statSync(filePath).isFile();
    }
    catch (_a) {
        return false;
    }
}
function resolveArtifactCandidate(candidate, roots) {
    var e_1, _a;
    var normalized = normalizeArtifactCandidatePath(candidate);
    if (!normalized) {
        return '';
    }
    if (path.isAbsolute(normalized)) {
        return pathExists(normalized) ? normalized : '';
    }
    try {
        for (var roots_1 = __values(roots), roots_1_1 = roots_1.next(); !roots_1_1.done; roots_1_1 = roots_1.next()) {
            var root = roots_1_1.value;
            var normalizedRoot = String(root || '').trim();
            if (!normalizedRoot) {
                continue;
            }
            var resolved = path.resolve(normalizedRoot, normalized);
            if (pathExists(resolved)) {
                return resolved;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (roots_1_1 && !roots_1_1.done && (_a = roots_1.return)) _a.call(roots_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return '';
}
function isEvidenceArtifactExtension(filePath, includeJson) {
    var ext = path.extname(String(filePath || '')).toLowerCase();
    return ext === '.png'
        || ext === '.jpg'
        || ext === '.jpeg'
        || ext === '.webp'
        || ext === '.zip'
        || (includeJson && ext === '.json');
}
function scoreEvidenceArtifactPath(filePath) {
    var baseName = path.basename(String(filePath || '')).toLowerCase();
    var ext = path.extname(baseName);
    var score = 0;
    if (['.png', '.jpg', '.jpeg', '.webp'].includes(ext)) {
        score += 100;
    }
    if (/\b(invoice|billing|surcharge|tax|inventory|transaction|location|chemical|item|truck|delivery|saved|submit|line|select|modal)\b/i.test(baseName)) {
        score += 60;
    }
    if (/\b(coverage|assert|result|summary|matrix)\b/i.test(baseName)) {
        score += 20;
    }
    if (/\b(auth|bootstrap|ready|client\.log|server\.log|runner|chrome)\b/i.test(baseName)) {
        score -= 120;
    }
    return score;
}
function collectEvidenceArtifactFilesFromDirectory(dirPath, includeJson, output, seen, depth) {
    var e_2, _a;
    if (depth === void 0) { depth = 0; }
    if (depth > 2) {
        return;
    }
    var entries = [];
    try {
        entries = fs.readdirSync(dirPath);
    }
    catch (_b) {
        return;
    }
    try {
        for (var entries_1 = __values(entries), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
            var entry = entries_1_1.value;
            var candidate = path.join(dirPath, entry);
            var stat = void 0;
            try {
                stat = fs.statSync(candidate);
            }
            catch (_c) {
                continue;
            }
            if (stat.isDirectory()) {
                collectEvidenceArtifactFilesFromDirectory(candidate, includeJson, output, seen, depth + 1);
                continue;
            }
            if (!stat.isFile() || stat.size <= 0 || !isEvidenceArtifactExtension(candidate, includeJson)) {
                continue;
            }
            var resolved = path.resolve(candidate);
            if (seen.has(resolved)) {
                continue;
            }
            seen.add(resolved);
            output.push({
                filePath: resolved,
                score: scoreEvidenceArtifactPath(resolved),
                mtimeMs: Number(stat.mtimeMs || 0)
            });
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (entries_1_1 && !entries_1_1.done && (_a = entries_1.return)) _a.call(entries_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
}
function collectResolveIORunnerEvidenceArtifactFilesFromRoots(input) {
    var e_3, _a, e_4, _b, e_5, _c;
    var _d;
    if (input === void 0) { input = {}; }
    var maxFiles = Math.max(1, Number(input.maxFiles || 12));
    var includeJson = input.includeJson !== false;
    var artifactDirNames = (((_d = input.artifactDirNames) === null || _d === void 0 ? void 0 : _d.length) ? input.artifactDirNames : ['qa-artifacts'])
        .map(function (entry) { return String(entry || '').trim(); })
        .filter(Boolean);
    var roots = Array.from(new Set((input.roots || [])
        .map(function (entry) { return String(entry || '').trim(); })
        .filter(Boolean)
        .map(function (entry) { return path.resolve(entry); })));
    var artifactDirs = new Set();
    try {
        for (var roots_2 = __values(roots), roots_2_1 = roots_2.next(); !roots_2_1.done; roots_2_1 = roots_2.next()) {
            var root = roots_2_1.value;
            var stat = null;
            try {
                stat = fs.statSync(root);
            }
            catch (_e) {
                stat = null;
            }
            if (!(stat === null || stat === void 0 ? void 0 : stat.isDirectory())) {
                continue;
            }
            var rootBaseName = path.basename(root);
            if (artifactDirNames.includes(rootBaseName)) {
                artifactDirs.add(root);
            }
            try {
                for (var artifactDirNames_1 = (e_4 = void 0, __values(artifactDirNames)), artifactDirNames_1_1 = artifactDirNames_1.next(); !artifactDirNames_1_1.done; artifactDirNames_1_1 = artifactDirNames_1.next()) {
                    var artifactDirName = artifactDirNames_1_1.value;
                    var directArtifactDir = path.join(root, artifactDirName);
                    try {
                        if (fs.statSync(directArtifactDir).isDirectory()) {
                            artifactDirs.add(directArtifactDir);
                        }
                    }
                    catch (_f) {
                        // Ignore missing artifact directories.
                    }
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (artifactDirNames_1_1 && !artifactDirNames_1_1.done && (_b = artifactDirNames_1.return)) _b.call(artifactDirNames_1);
                }
                finally { if (e_4) throw e_4.error; }
            }
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (roots_2_1 && !roots_2_1.done && (_a = roots_2.return)) _a.call(roots_2);
        }
        finally { if (e_3) throw e_3.error; }
    }
    var seen = new Set();
    var files = [];
    try {
        for (var artifactDirs_1 = __values(artifactDirs), artifactDirs_1_1 = artifactDirs_1.next(); !artifactDirs_1_1.done; artifactDirs_1_1 = artifactDirs_1.next()) {
            var artifactDir = artifactDirs_1_1.value;
            collectEvidenceArtifactFilesFromDirectory(artifactDir, includeJson, files, seen);
        }
    }
    catch (e_5_1) { e_5 = { error: e_5_1 }; }
    finally {
        try {
            if (artifactDirs_1_1 && !artifactDirs_1_1.done && (_c = artifactDirs_1.return)) _c.call(artifactDirs_1);
        }
        finally { if (e_5) throw e_5.error; }
    }
    return files
        .sort(function (left, right) {
        if (right.score !== left.score) {
            return right.score - left.score;
        }
        if (left.mtimeMs !== right.mtimeMs) {
            return left.mtimeMs - right.mtimeMs;
        }
        return left.filePath.localeCompare(right.filePath);
    })
        .slice(0, maxFiles)
        .map(function (entry) { return entry.filePath; });
}
function toResolveIORunnerEvidenceAttachmentsFromRoots(input) {
    if (input === void 0) { input = {}; }
    return collectResolveIORunnerEvidenceArtifactFilesFromRoots(input).map(function (filePath) {
        var filename = path.basename(filePath);
        return {
            filename: filename,
            path: filePath,
            contentType: inferResolveIORunnerEvidenceContentType(filename),
            cid: buildResolveIORunnerEvidenceCid(filePath),
            caption: inferResolveIORunnerEvidenceCaption(filename)
        };
    });
}
function collectResolveIORunnerEvidenceArtifactPaths(input) {
    var e_6, _a, e_7, _b, e_8, _c, e_9, _d, e_10, _e;
    var _f, _g, _h, _j;
    if (input === void 0) { input = {}; }
    var values = [];
    collectResolveIORunnerEvidenceText(input.evidence, values);
    var job = input.job || {};
    collectResolveIORunnerEvidenceText(job.responseSummary, values);
    collectResolveIORunnerEvidenceText(job.lastVerificationSummary, values);
    collectResolveIORunnerEvidenceText(job.lastRerunReason, values);
    collectResolveIORunnerEvidenceText((_f = job.artifacts) === null || _f === void 0 ? void 0 : _f.agentNotes, values);
    collectResolveIORunnerEvidenceText((_g = job.artifacts) === null || _g === void 0 ? void 0 : _g.supportArtifacts, values);
    collectResolveIORunnerEvidenceText((_h = job.artifacts) === null || _h === void 0 ? void 0 : _h.qaArtifacts, values);
    collectResolveIORunnerEvidenceText((_j = job.artifacts) === null || _j === void 0 ? void 0 : _j.qa_artifacts, values);
    collectResolveIORunnerEvidenceText(job.qa_artifacts, values);
    collectResolveIORunnerEvidenceText(job.supportQaArtifacts, values);
    collectResolveIORunnerEvidenceText(job.runnerEvidenceArtifacts, values);
    if (Array.isArray(job.tasks)) {
        try {
            for (var _k = __values(job.tasks), _l = _k.next(); !_l.done; _l = _k.next()) {
                var task = _l.value;
                collectResolveIORunnerEvidenceText(task === null || task === void 0 ? void 0 : task.title, values);
                collectResolveIORunnerEvidenceText(task === null || task === void 0 ? void 0 : task.notes, values);
                collectResolveIORunnerEvidenceText(task === null || task === void 0 ? void 0 : task.artifacts, values);
                collectResolveIORunnerEvidenceText(task === null || task === void 0 ? void 0 : task.evidence, values);
            }
        }
        catch (e_6_1) { e_6 = { error: e_6_1 }; }
        finally {
            try {
                if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
            }
            finally { if (e_6) throw e_6.error; }
        }
    }
    if (Array.isArray(job.log)) {
        collectResolveIORunnerEvidenceText(job.log.slice(-160), values);
    }
    var roots = Array.from(new Set(__spreadArray(__spreadArray([], __read((input.roots || [])), false), [
        job.workspacePath,
        job.projectRoot && job.workspacePath ? path.join(job.workspacePath, job.projectRoot) : '',
        job.projectDisplayPath && job.workspacePath ? path.join(job.workspacePath, job.projectDisplayPath) : '',
        job.localPath
    ], false).map(function (entry) { return String(entry || '').trim(); }).filter(Boolean)));
    var candidates = [];
    try {
        for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
            var value = values_1_1.value;
            var text = String(value || '');
            try {
                for (var _m = (e_8 = void 0, __values(text.matchAll(/((?:\/tmp\/|\/var\/|\/Users\/)[^\s)'"]+?\.(?:png|jpe?g|webp|zip|json|txt|log))/gi))), _o = _m.next(); !_o.done; _o = _m.next()) {
                    var match = _o.value;
                    candidates.push(match[1]);
                }
            }
            catch (e_8_1) { e_8 = { error: e_8_1 }; }
            finally {
                try {
                    if (_o && !_o.done && (_c = _m.return)) _c.call(_m);
                }
                finally { if (e_8) throw e_8.error; }
            }
            try {
                for (var _p = (e_9 = void 0, __values(text.matchAll(/(?:^|[\s("'`])((?:(?:[\w.-]+\/)*qa-artifacts|qa-artifacts|test-results|playwright-report|\.build-output)\/[^\s)'"]+?\.(?:png|jpe?g|webp|zip|json|txt|log))/gim))), _q = _p.next(); !_q.done; _q = _p.next()) {
                    var match = _q.value;
                    candidates.push(match[1]);
                }
            }
            catch (e_9_1) { e_9 = { error: e_9_1 }; }
            finally {
                try {
                    if (_q && !_q.done && (_d = _p.return)) _d.call(_p);
                }
                finally { if (e_9) throw e_9.error; }
            }
        }
    }
    catch (e_7_1) { e_7 = { error: e_7_1 }; }
    finally {
        try {
            if (values_1_1 && !values_1_1.done && (_b = values_1.return)) _b.call(values_1);
        }
        finally { if (e_7) throw e_7.error; }
    }
    var resolved = [];
    var seen = new Set();
    try {
        for (var candidates_1 = __values(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
            var candidate = candidates_1_1.value;
            var filePath = resolveArtifactCandidate(candidate, roots);
            if (!filePath || seen.has(filePath)) {
                continue;
            }
            seen.add(filePath);
            resolved.push(filePath);
            if (resolved.length >= (input.maxFiles || 8)) {
                break;
            }
        }
    }
    catch (e_10_1) { e_10 = { error: e_10_1 }; }
    finally {
        try {
            if (candidates_1_1 && !candidates_1_1.done && (_e = candidates_1.return)) _e.call(candidates_1);
        }
        finally { if (e_10) throw e_10.error; }
    }
    return resolved;
}
function toResolveIORunnerEvidenceAttachments(input) {
    if (input === void 0) { input = {}; }
    return collectResolveIORunnerEvidenceArtifactPaths(input).map(function (filePath) {
        var filename = path.basename(filePath);
        return {
            filename: filename,
            path: filePath,
            contentType: inferResolveIORunnerEvidenceContentType(filename),
            cid: buildResolveIORunnerEvidenceCid(filePath),
            caption: inferResolveIORunnerEvidenceCaption(filename)
        };
    });
}
function persistResolveIORunnerEvidenceArtifacts(options) {
    return __awaiter(this, void 0, void 0, function () {
        var maxFiles, previousFiles, existingByHash, previousFiles_1, previousFiles_1_1, file, attachments, persistedFiles, fileIds, errors, nextAttachments, seenPaths, attachments_1, attachments_1_1, attachment, filePath, filename, contentType, error, stat, error, contentBuffer, contentHash, existing, uploaded, fileId, persisted, error_1, message, e_11_1;
        var e_12, _a, e_11, _b;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    maxFiles = Math.max(1, options.maxFiles || 8);
                    previousFiles = normalizeResolveIORunnerPersistedEvidenceFiles(options.previousFiles);
                    existingByHash = new Map();
                    try {
                        for (previousFiles_1 = __values(previousFiles), previousFiles_1_1 = previousFiles_1.next(); !previousFiles_1_1.done; previousFiles_1_1 = previousFiles_1.next()) {
                            file = previousFiles_1_1.value;
                            if (file.content_hash) {
                                existingByHash.set(file.content_hash, file);
                            }
                        }
                    }
                    catch (e_12_1) { e_12 = { error: e_12_1 }; }
                    finally {
                        try {
                            if (previousFiles_1_1 && !previousFiles_1_1.done && (_a = previousFiles_1.return)) _a.call(previousFiles_1);
                        }
                        finally { if (e_12) throw e_12.error; }
                    }
                    attachments = __spreadArray(__spreadArray([], __read((options.attachments || [])), false), __read(toResolveIORunnerEvidenceAttachments({
                        evidence: options.evidence,
                        job: options.job,
                        roots: options.roots,
                        maxFiles: maxFiles
                    })), false);
                    persistedFiles = __spreadArray([], __read(previousFiles), false);
                    fileIds = mergeResolveIORunnerEvidenceFileIds(options.existingFileIds, previousFiles.map(function (file) { return file.file_id; }));
                    errors = [];
                    nextAttachments = [];
                    seenPaths = new Set();
                    _c.label = 1;
                case 1:
                    _c.trys.push([1, 10, 11, 12]);
                    attachments_1 = __values(attachments), attachments_1_1 = attachments_1.next();
                    _c.label = 2;
                case 2:
                    if (!!attachments_1_1.done) return [3 /*break*/, 9];
                    attachment = attachments_1_1.value;
                    if (nextAttachments.length >= maxFiles) {
                        return [3 /*break*/, 9];
                    }
                    filePath = String((attachment === null || attachment === void 0 ? void 0 : attachment.path) || '').trim();
                    if (!filePath || seenPaths.has(filePath)) {
                        return [3 /*break*/, 8];
                    }
                    seenPaths.add(filePath);
                    filename = String((attachment === null || attachment === void 0 ? void 0 : attachment.filename) || path.basename(filePath) || 'runner-qa-artifact.png').trim();
                    contentType = String((attachment === null || attachment === void 0 ? void 0 : attachment.contentType) || inferResolveIORunnerEvidenceContentType(filename)).trim();
                    if (!pathExists(filePath)) {
                        error = "".concat(filename, ": evidence file was not found before S3 upload.");
                        errors.push(error);
                        nextAttachments.push(__assign(__assign({}, attachment), { filename: filename, upload_error: error }));
                        return [3 /*break*/, 8];
                    }
                    return [4 /*yield*/, fs.promises.stat(filePath)];
                case 3:
                    stat = _c.sent();
                    if (!stat.isFile() || stat.size <= 0) {
                        error = "".concat(filename, ": evidence file was empty before S3 upload.");
                        errors.push(error);
                        nextAttachments.push(__assign(__assign({}, attachment), { filename: filename, upload_error: error }));
                        return [3 /*break*/, 8];
                    }
                    return [4 /*yield*/, fs.promises.readFile(filePath)];
                case 4:
                    contentBuffer = _c.sent();
                    contentHash = (0, node_crypto_1.createHash)('sha1').update(new Uint8Array(contentBuffer)).digest('hex');
                    existing = existingByHash.get(contentHash);
                    if (existing) {
                        fileIds.push(existing.file_id);
                        nextAttachments.push(__assign(__assign({}, attachment), { filename: filename, file_id: existing.file_id, key: existing.key, caption: attachment.caption || existing.caption || inferResolveIORunnerEvidenceCaption(filename), content_hash: contentHash, ticket_url: options.ticketUrl || existing.ticket_url, uploaded_to_support_ticket: true }));
                        return [3 /*break*/, 8];
                    }
                    _c.label = 5;
                case 5:
                    _c.trys.push([5, 7, , 8]);
                    return [4 /*yield*/, options.uploadFile({
                            filename: filename,
                            filePath: filePath,
                            contentType: contentType,
                            size: stat.size,
                            contentBuffer: contentBuffer,
                            contentHash: contentHash
                        })];
                case 6:
                    uploaded = _c.sent();
                    fileId = String((uploaded === null || uploaded === void 0 ? void 0 : uploaded.file_id) || (uploaded === null || uploaded === void 0 ? void 0 : uploaded.id_file) || (uploaded === null || uploaded === void 0 ? void 0 : uploaded._id) || '').trim();
                    if (!fileId) {
                        throw new Error('artifact upload returned no file id');
                    }
                    persisted = {
                        file_id: fileId,
                        filename: String((uploaded === null || uploaded === void 0 ? void 0 : uploaded.filename) || (uploaded === null || uploaded === void 0 ? void 0 : uploaded.name) || filename).trim() || filename,
                        key: String((uploaded === null || uploaded === void 0 ? void 0 : uploaded.key) || '').trim() || undefined,
                        contentType: contentType,
                        caption: String((attachment === null || attachment === void 0 ? void 0 : attachment.caption) || '').trim() || inferResolveIORunnerEvidenceCaption(filename),
                        content_hash: contentHash,
                        ticket_url: String(options.ticketUrl || '').trim() || undefined
                    };
                    persistedFiles.push(persisted);
                    existingByHash.set(contentHash, persisted);
                    fileIds.push(fileId);
                    nextAttachments.push(__assign(__assign({}, attachment), { filename: filename, file_id: fileId, key: persisted.key, caption: persisted.caption, content_hash: contentHash, ticket_url: persisted.ticket_url, uploaded_to_support_ticket: true }));
                    return [3 /*break*/, 8];
                case 7:
                    error_1 = _c.sent();
                    message = "".concat(filename, ": ").concat((error_1 === null || error_1 === void 0 ? void 0 : error_1.message) || error_1);
                    errors.push(message);
                    nextAttachments.push(__assign(__assign({}, attachment), { filename: filename, content_hash: contentHash, upload_error: message }));
                    return [3 /*break*/, 8];
                case 8:
                    attachments_1_1 = attachments_1.next();
                    return [3 /*break*/, 2];
                case 9: return [3 /*break*/, 12];
                case 10:
                    e_11_1 = _c.sent();
                    e_11 = { error: e_11_1 };
                    return [3 /*break*/, 12];
                case 11:
                    try {
                        if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
                    }
                    finally { if (e_11) throw e_11.error; }
                    return [7 /*endfinally*/];
                case 12: return [2 /*return*/, {
                        attachments: nextAttachments,
                        fileIds: mergeResolveIORunnerEvidenceFileIds(fileIds),
                        files: persistedFiles,
                        errors: errors
                    }];
            }
        });
    });
}

//# sourceMappingURL=ai-runner-artifacts.js.map
