import md5 from 'md5';
import { resolve as urlResolve } from 'node:url';
import path from 'node:path';
const normalizeFilePathInRemoteRepo = (repo, path) => {
    return urlResolve(repo.endsWith('/') ? repo : `${repo}/`, path);
};
const normalizeFilePathInLocalRepo = (repoId, specmaticJsonPath, specPath) => {
    return `${repoId}:${path.relative(process.cwd(), path.resolve(path.dirname(specmaticJsonPath), specPath))}`;
};
const getSpecId = (report, coverageOrStub) => {
    if (coverageOrStub.repository) {
        // There's a central repo setup for contracts
        return md5(normalizeFilePathInRemoteRepo(coverageOrStub.repository, coverageOrStub.specification));
    }
    // Contract is within the same repo
    return md5(normalizeFilePathInLocalRepo(report.repoId, 
    // We're checking before calling this function that specmaticConfigPath is defined
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    report.specmaticConfigPath, coverageOrStub.specification));
};
export const processSpecmaticData = (report) => {
    var _a, _b;
    if (!report.specmaticConfigPath)
        return {};
    return {
        specmaticConfigPath: report.specmaticConfigPath,
        specmaticCoverage: (_a = report.specmaticCoverage) === null || _a === void 0 ? void 0 : _a.map(coverage => {
            return { ...coverage, specId: getSpecId(report, coverage) };
        }),
        specmaticStubUsage: (_b = report.specmaticStubUsage) === null || _b === void 0 ? void 0 : _b.map(stubUsage => {
            return { ...stubUsage, specId: getSpecId(report, stubUsage) };
        }),
    };
};
const getSpecIdForCentralRepo = (repoUrl) => (specification) => {
    // if (/* we're in a mono-repo */) {
    //   return /* the spec id */;
    // } else ...
    return md5(normalizeFilePathInRemoteRepo(repoUrl, specification));
};
export const processSpecmaticCentralRepoReport = (report) => {
    if (!report.specmaticCentralRepoReport)
        return {};
    const getSpecId = getSpecIdForCentralRepo(report.repoUrl);
    return {
        specmaticCentralRepoReport: report.specmaticCentralRepoReport.map(x => ({
            ...x,
            specId: getSpecId(x.specification),
        })),
    };
};
