import { promises as fs } from 'node:fs';
import { join } from 'node:path';
import debug from 'debug';
import pluralize from 'pluralize';
const outputFileLog = debug('write-output');
const dataFolderPath = join(process.cwd(), 'data');
const writeFile = async (path, fileName, contents) => {
    outputFileLog('Writing', join(dataFolderPath, ...path, fileName).replace(`${process.cwd()}/`, ''));
    await fs.mkdir(join(dataFolderPath, ...path), { recursive: true });
    return fs.writeFile(join(dataFolderPath, ...path, fileName), contents, 'utf8');
};
const projectSummary = (collectionName, projectConfig, projectAnalysis) => {
    var _a, _b;
    return ({
        name: [collectionName, projectConfig.name],
        lastUpdated: new Date().toISOString(),
        reposCount: projectAnalysis.repoAnalysis.length,
        releasePipelineCount: projectAnalysis.releaseAnalysis.pipelines.length,
        workItemCount: Object.values(((_b = (_a = projectAnalysis.workItemAnalysis) === null || _a === void 0 ? void 0 : _a.analysedWorkItems) === null || _b === void 0 ? void 0 : _b.ids[0]) || {})
            .length || 0,
        workItemLabel: [
            pluralize.singular(projectAnalysis.workItemLabel),
            projectAnalysis.workItemLabel,
        ],
    });
};
const writeRepoAnalysisFile = async (collectionName, projectConfig, projectAnalysis) => {
    const analysis = {
        ...projectSummary(collectionName, projectConfig, projectAnalysis),
        repos: projectAnalysis.repoAnalysis,
        featureToggles: projectAnalysis.featureToggles,
        groups: projectConfig.groupRepos,
    };
    return writeFile([collectionName, projectConfig.name], 'repos.json', JSON.stringify(analysis));
};
const writeReleaseAnalysisFile = async (collectionName, projectConfig, projectAnalysis) => {
    var _a, _b;
    const analysis = {
        ...projectSummary(collectionName, projectConfig, projectAnalysis),
        ...projectAnalysis.releaseAnalysis,
        stagesToHighlight: (_a = projectConfig.releasePipelines) === null || _a === void 0 ? void 0 : _a.stagesToHighlight,
        ignoreStagesBefore: (_b = projectConfig.releasePipelines) === null || _b === void 0 ? void 0 : _b.ignoreStagesBefore,
        groups: projectConfig.groupRepos,
        environments: projectConfig.environments,
    };
    return writeFile([collectionName, projectConfig.name], 'releases.json', JSON.stringify(analysis));
};
const writeWorkItemAnalysisFile = async (collectionName, projectConfig, projectAnalysis) => {
    const analysis = {
        ...projectSummary(collectionName, projectConfig, projectAnalysis),
        workItems: projectAnalysis.workItemAnalysis.analysedWorkItems,
        taskType: projectConfig.workitems.label,
    };
    return writeFile([collectionName, projectConfig.name], 'work-items.json', JSON.stringify(analysis));
};
const writeOverviewFile = async (collectionName, projectConfig, projectAnalysis) => {
    var _a;
    const analysis = {
        ...projectSummary(collectionName, projectConfig, projectAnalysis),
        overview: (_a = projectAnalysis.workItemAnalysis) === null || _a === void 0 ? void 0 : _a.overview,
        testCases: projectAnalysis.testCasesAnalysis,
        ignoreForWIP: projectConfig.workitems.ignoreForWIP,
        environments: projectConfig.environments,
    };
    return writeFile([collectionName, projectConfig.name], 'overview.json', JSON.stringify(analysis));
};
export default (collectionName, projectConfig) => (analysis) => Promise.all([
    writeRepoAnalysisFile(collectionName, projectConfig, analysis),
    writeReleaseAnalysisFile(collectionName, projectConfig, analysis),
    writeWorkItemAnalysisFile(collectionName, projectConfig, analysis),
    writeOverviewFile(collectionName, projectConfig, analysis),
]);
export const writeSummaryMetricsFile = (summary) => writeFile(['./'], 'summary-metrics.json', JSON.stringify(summary));
export const writeTrackFlowMetrics = (tracks) => {
    const tracksWorkItems = {
        tracks,
        lastUpdated: new Date().toISOString(),
    };
    return writeFile(['./'], 'track-flow-metrics.json', JSON.stringify(tracksWorkItems));
};
export const writeTrackFeatures = (tracks) => {
    const tracksWorkItems = {
        tracks,
        lastUpdated: new Date().toISOString(),
    };
    return writeFile(['./'], 'track-features.json', JSON.stringify(tracksWorkItems));
};
export const writeChangeProgramFile = (config) => (tasks) => {
    const someCollectionWithChangeProgram = config.azure.collections.find(c => c.changeProgram);
    const changeProgram = {
        lastUpdated: new Date().toISOString(),
        details: someCollectionWithChangeProgram
            ? {
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                taskName: someCollectionWithChangeProgram.changeProgram.workItemTypeName,
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                name: someCollectionWithChangeProgram.changeProgram.name,
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                startedState: someCollectionWithChangeProgram.changeProgram.startedState,
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                doneState: someCollectionWithChangeProgram.changeProgram.doneState,
                tasks,
            }
            : null,
    };
    return writeFile(['./'], 'change-program.json', JSON.stringify(changeProgram));
};
