import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, unlinkSync } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { getMidsceneRunSubDir } from "@midscene/shared/common";
import { logMsg } from "@midscene/shared/utils";
import { getReportFileName } from "./agent/index.mjs";
import { BASE_URL_FIX_SCRIPT, extractLastDumpScriptSync, streamImageScriptsToFile } from "./dump/html-utils.mjs";
import { getReportTpl, reportHTMLContent } from "./utils.mjs";
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
class ReportMergingTool {
    append(reportInfo) {
        this.reportInfos.push(reportInfo);
    }
    clear() {
        this.reportInfos = [];
    }
    isDirectoryModeReport(reportFilePath) {
        const reportDir = dirname(reportFilePath);
        return 'index.html' === basename(reportFilePath) && existsSync(join(reportDir, 'screenshots'));
    }
    mergeReports(reportFileName = 'AUTO', opts) {
        if (this.reportInfos.length <= 1) {
            logMsg('Not enough reports to merge');
            return null;
        }
        const { rmOriginalReports = false, overwrite = false } = opts ?? {};
        const targetDir = getMidsceneRunSubDir('report');
        const hasDirectoryModeReport = this.reportInfos.some((info)=>this.isDirectoryModeReport(info.reportFilePath));
        const resolvedName = 'AUTO' === reportFileName ? getReportFileName('merged-report') : reportFileName;
        const outputFilePath = hasDirectoryModeReport ? resolve(targetDir, resolvedName, 'index.html') : resolve(targetDir, `${resolvedName}.html`);
        if ('AUTO' !== reportFileName && existsSync(outputFilePath)) {
            if (!overwrite) throw new Error(`Report file already exists: ${outputFilePath}\nSet overwrite to true to overwrite this file.`);
            if (hasDirectoryModeReport) rmSync(dirname(outputFilePath), {
                recursive: true,
                force: true
            });
            else unlinkSync(outputFilePath);
        }
        if (hasDirectoryModeReport) mkdirSync(dirname(outputFilePath), {
            recursive: true
        });
        logMsg(`Start merging ${this.reportInfos.length} reports...\nCreating template file...`);
        try {
            appendFileSync(outputFilePath, getReportTpl());
            if (hasDirectoryModeReport) appendFileSync(outputFilePath, BASE_URL_FIX_SCRIPT);
            for(let i = 0; i < this.reportInfos.length; i++){
                const reportInfo = this.reportInfos[i];
                logMsg(`Processing report ${i + 1}/${this.reportInfos.length}`);
                if (this.isDirectoryModeReport(reportInfo.reportFilePath)) {
                    const reportDir = dirname(reportInfo.reportFilePath);
                    const screenshotsDir = join(reportDir, 'screenshots');
                    const mergedScreenshotsDir = join(dirname(outputFilePath), 'screenshots');
                    mkdirSync(mergedScreenshotsDir, {
                        recursive: true
                    });
                    for (const file of readdirSync(screenshotsDir)){
                        const src = join(screenshotsDir, file);
                        const dest = join(mergedScreenshotsDir, file);
                        copyFileSync(src, dest);
                    }
                } else streamImageScriptsToFile(reportInfo.reportFilePath, outputFilePath);
                const dumpString = extractLastDumpScriptSync(reportInfo.reportFilePath);
                const { reportAttributes } = reportInfo;
                const reportHtmlStr = `${reportHTMLContent({
                    dumpString,
                    attributes: {
                        playwright_test_duration: reportAttributes.testDuration,
                        playwright_test_status: reportAttributes.testStatus,
                        playwright_test_title: reportAttributes.testTitle,
                        playwright_test_id: reportAttributes.testId,
                        playwright_test_description: reportAttributes.testDescription
                    }
                }, void 0, void 0, false)}\n`;
                appendFileSync(outputFilePath, reportHtmlStr);
            }
            logMsg(`Successfully merged new report: ${outputFilePath}`);
            if (rmOriginalReports) {
                for (const info of this.reportInfos)try {
                    if (this.isDirectoryModeReport(info.reportFilePath)) {
                        const reportDir = dirname(info.reportFilePath);
                        rmSync(reportDir, {
                            recursive: true,
                            force: true
                        });
                    } else unlinkSync(info.reportFilePath);
                } catch (error) {
                    logMsg(`Error deleting report ${info.reportFilePath}: ${error}`);
                }
                logMsg(`Removed ${this.reportInfos.length} original reports`);
            }
            return outputFilePath;
        } catch (error) {
            logMsg(`Error in mergeReports: ${error}`);
            throw error;
        }
    }
    constructor(){
        _define_property(this, "reportInfos", []);
    }
}
export { ReportMergingTool };

//# sourceMappingURL=report.mjs.map