"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    createReportCliCommands: ()=>createReportCliCommands,
    reportFileToMarkdown: ()=>reportFileToMarkdown,
    mergeReportFiles: ()=>mergeReportFiles,
    splitReportFile: ()=>splitReportFile
});
const external_node_fs_namespaceObject = require("node:fs");
const external_node_path_namespaceObject = require("node:path");
const external_zod_namespaceObject = require("zod");
const screenshot_store_js_namespaceObject = require("./dump/screenshot-store.js");
const external_report_js_namespaceObject = require("./report.js");
const external_report_markdown_js_namespaceObject = require("./report-markdown.js");
const external_types_js_namespaceObject = require("./types.js");
function writeAttachmentFromReport(attachment, opts) {
    const { suggestedFileName, id, mimeType } = attachment;
    if (opts.writtenFiles.has(suggestedFileName)) return;
    const absolutePath = external_node_path_namespaceObject.join(opts.screenshotsDir, suggestedFileName);
    const resolved = (0, screenshot_store_js_namespaceObject.resolveScreenshotSource)(attachment.sourceRef ?? null, {
        reportPath: opts.htmlPath,
        fallbackId: id,
        fallbackMimeType: mimeType || 'image/png'
    });
    if ('data-uri' === resolved.type) {
        const rawBase64 = resolved.dataUri.replace(/^data:image\/[a-zA-Z+]+;base64,/, '');
        (0, external_node_fs_namespaceObject.writeFileSync)(absolutePath, Buffer.from(rawBase64, 'base64'));
        opts.writtenFiles.add(suggestedFileName);
        return;
    }
    if (!(0, external_node_fs_namespaceObject.existsSync)(resolved.filePath)) throw new Error(`Cannot resolve screenshot "${id}" for markdown attachment from ${opts.htmlPath}`);
    (0, external_node_fs_namespaceObject.copyFileSync)(resolved.filePath, absolutePath);
    opts.writtenFiles.add(suggestedFileName);
}
async function markdownFromReport(htmlPath, outputDir) {
    const screenshotsDir = external_node_path_namespaceObject.join(outputDir, 'screenshots');
    (0, external_node_fs_namespaceObject.mkdirSync)(outputDir, {
        recursive: true
    });
    (0, external_node_fs_namespaceObject.mkdirSync)(screenshotsDir, {
        recursive: true
    });
    const { baseDump, executions } = (0, external_report_js_namespaceObject.collectDedupedExecutions)(htmlPath);
    const mergedReport = new external_types_js_namespaceObject.ReportActionDump({
        sdkVersion: baseDump.sdkVersion,
        groupName: baseDump.groupName,
        groupDescription: baseDump.groupDescription,
        modelBriefs: baseDump.modelBriefs,
        deviceType: baseDump.deviceType,
        executions
    });
    const result = (0, external_report_markdown_js_namespaceObject.reportToMarkdown)(mergedReport);
    const markdownFiles = [];
    const writtenScreenshots = new Set();
    const mdPath = external_node_path_namespaceObject.join(outputDir, 'report.md');
    (0, external_node_fs_namespaceObject.writeFileSync)(mdPath, result.markdown, 'utf-8');
    markdownFiles.push(mdPath);
    for (const attachment of result.attachments)writeAttachmentFromReport(attachment, {
        htmlPath,
        screenshotsDir,
        writtenFiles: writtenScreenshots
    });
    return {
        markdownFiles,
        screenshotFiles: Array.from(writtenScreenshots).sort().map((f)=>external_node_path_namespaceObject.join(screenshotsDir, f))
    };
}
function resolveReportHtmlPath(htmlPath) {
    const normalizedPath = external_node_path_namespaceObject.resolve(htmlPath);
    if (!(0, external_node_fs_namespaceObject.existsSync)(normalizedPath)) throw new Error(`report-tool: --htmlPath does not exist: ${htmlPath}`);
    const stats = (0, external_node_fs_namespaceObject.statSync)(normalizedPath);
    if (!stats.isDirectory()) return normalizedPath;
    const indexHtmlPath = external_node_path_namespaceObject.join(normalizedPath, 'index.html');
    if (!(0, external_node_fs_namespaceObject.existsSync)(indexHtmlPath)) throw new Error(`report-tool: "${htmlPath}" is not an HTML report file, and no index.html was found under this directory.`);
    return indexHtmlPath;
}
function splitReportFile(options) {
    const { htmlPath, outputDir } = options;
    if (!htmlPath) throw new Error('splitReportFile: htmlPath is required');
    if (!outputDir) throw new Error('splitReportFile: outputDir is required');
    const resolvedHtmlPath = resolveReportHtmlPath(htmlPath);
    return (0, external_report_js_namespaceObject.splitReportHtmlByExecution)({
        htmlPath: resolvedHtmlPath,
        outputDir
    });
}
async function reportFileToMarkdown(options) {
    const { htmlPath, outputDir } = options;
    if (!htmlPath) throw new Error('reportFileToMarkdown: htmlPath is required');
    if (!outputDir) throw new Error('reportFileToMarkdown: outputDir is required');
    const resolvedHtmlPath = resolveReportHtmlPath(htmlPath);
    return markdownFromReport(resolvedHtmlPath, outputDir);
}
function deriveReportAttributesFromHtml(htmlPath, index) {
    const fallbackId = `${external_node_path_namespaceObject.basename(external_node_path_namespaceObject.dirname(htmlPath)) || external_node_path_namespaceObject.basename(htmlPath, external_node_path_namespaceObject.extname(htmlPath))}-${index + 1}`;
    try {
        const { baseDump } = (0, external_report_js_namespaceObject.collectDedupedExecutions)(htmlPath);
        return {
            testId: fallbackId,
            testTitle: baseDump.groupName || fallbackId,
            testDescription: baseDump.groupDescription ?? '',
            testDuration: 0,
            testStatus: 'passed'
        };
    } catch  {
        return {
            testId: fallbackId,
            testTitle: fallbackId,
            testDescription: '',
            testDuration: 0,
            testStatus: 'passed'
        };
    }
}
function mergeReportFiles(options) {
    const { htmlPaths, outputDir, outputName, overwrite = false } = options;
    if (!htmlPaths || 0 === htmlPaths.length) throw new Error('mergeReportFiles: htmlPaths is required');
    const resolvedPaths = htmlPaths.map((p)=>resolveReportHtmlPath(p));
    const tool = new external_report_js_namespaceObject.ReportMergingTool();
    resolvedPaths.forEach((htmlPath, index)=>{
        tool.append({
            reportFilePath: htmlPath,
            reportAttributes: deriveReportAttributesFromHtml(htmlPath, index)
        });
    });
    const mergedReportPath = tool.mergeReports(outputName ?? 'AUTO', {
        overwrite,
        outputDir
    });
    if (!mergedReportPath) throw new Error('mergeReportFiles: failed to produce a merged report');
    return {
        mergedReportPath
    };
}
function normalizeHtmlReportArg(raw) {
    if (null == raw) return;
    if (Array.isArray(raw)) return raw.filter((p)=>'string' == typeof p && p.length > 0);
    if ('string' == typeof raw) {
        const trimmed = raw.trim();
        return trimmed ? [
            trimmed
        ] : [];
    }
}
const reportCommandDefinition = {
    name: 'report-tool',
    description: 'Transform Midscene report artifacts, including splitting executions, converting to markdown, and merging multiple reports.',
    schema: {
        action: external_zod_namespaceObject.z["enum"]([
            'split',
            'to-markdown',
            'merge-html'
        ]).optional().describe('Report action to run. Supports: split, to-markdown, merge-html. Defaults to split.'),
        htmlPath: external_zod_namespaceObject.z.string().optional().describe('Input report HTML path (e.g. ./report/index.html). Used by split and to-markdown.'),
        htmlReport: external_zod_namespaceObject.z.union([
            external_zod_namespaceObject.z.string(),
            external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())
        ]).optional().describe('Input report HTML path for the merge action. Repeat the flag to merge multiple reports (e.g. --htmlReport ./a/index.html --htmlReport ./b.html).'),
        outputDir: external_zod_namespaceObject.z.string().optional().describe('Output directory for generated report artifacts. For merge, defaults to the Midscene report directory.'),
        outputName: external_zod_namespaceObject.z.string().optional().describe('Output report file/directory name (without .html) for the merge action. Defaults to an auto-generated name.'),
        overwrite: external_zod_namespaceObject.z.union([
            external_zod_namespaceObject.z.boolean(),
            external_zod_namespaceObject.z.string()
        ]).optional().describe('Overwrite the existing merged report file if present (merge action only).')
    },
    handler: async (args)=>{
        const { action = 'split', htmlPath, htmlReport, outputDir, outputName, overwrite } = args;
        if ('split' !== action && 'to-markdown' !== action && 'merge-html' !== action) throw new Error(`report-tool: unsupported --action value "${action}". Currently supported: split, to-markdown, merge-html`);
        if ('merge-html' === action) {
            const paths = normalizeHtmlReportArg(htmlReport);
            if (!paths || 0 === paths.length) throw new Error('report-tool: --htmlReport is required for action "merge-html". Repeat --htmlReport for each report (e.g. --htmlReport ./a/index.html --htmlReport ./b.html).');
            const overwriteFlag = true === overwrite || 'true' === overwrite || '1' === overwrite;
            const result = mergeReportFiles({
                htmlPaths: paths,
                outputDir,
                outputName,
                overwrite: overwriteFlag
            });
            return {
                isError: false,
                content: [
                    {
                        type: 'text',
                        text: `Merged ${paths.length} report(s) into ${result.mergedReportPath}`
                    }
                ]
            };
        }
        if (!htmlPath) throw new Error('report-tool: --htmlPath is required');
        if (!outputDir) throw new Error('report-tool: --outputDir is required');
        if ('to-markdown' === action) {
            const result = await reportFileToMarkdown({
                htmlPath,
                outputDir
            });
            return {
                isError: false,
                content: [
                    {
                        type: 'text',
                        text: `Markdown export completed. Generated ${result.markdownFiles.length} markdown file(s) and ${result.screenshotFiles.length} screenshot(s). Output path: ${outputDir}`
                    }
                ]
            };
        }
        const result = splitReportFile({
            htmlPath,
            outputDir
        });
        return {
            isError: false,
            content: [
                {
                    type: 'text',
                    text: `Report split completed. Generated ${result.executionJsonFiles.length} execution JSON files and ${result.screenshotFiles.length} screenshots. Output path: ${outputDir}`
                }
            ]
        };
    }
};
function createReportCliCommands() {
    return [
        {
            name: 'report-tool',
            def: reportCommandDefinition
        }
    ];
}
exports.createReportCliCommands = __webpack_exports__.createReportCliCommands;
exports.mergeReportFiles = __webpack_exports__.mergeReportFiles;
exports.reportFileToMarkdown = __webpack_exports__.reportFileToMarkdown;
exports.splitReportFile = __webpack_exports__.splitReportFile;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "createReportCliCommands",
    "mergeReportFiles",
    "reportFileToMarkdown",
    "splitReportFile"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=report-cli.js.map