"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadRecentRepoResults = loadRecentRepoResults;
exports.logServiceEvent = logServiceEvent;
exports.buildRepoEventBase = buildRepoEventBase;
const branding_1 = require("../../core/branding");
const file_readers_1 = require("../../core/file-readers");
const paths_1 = require("../../core/paths");
const shared_1 = require("../service/shared");
const tracked_project_1 = require("./tracked-project");
const SERVICE_EVENT_PREFIX = `[${branding_1.CLI_COMMAND_NAME}-service]`;
async function loadRecentRepoResults(homeDirectory) {
    const logPath = (0, paths_1.getServiceLogPath)(homeDirectory);
    const text = await (0, file_readers_1.readTextFileIfExists)(logPath);
    if (text === null) {
        return new Map();
    }
    const results = new Map();
    for (const line of text.split("\n")) {
        if (!line.startsWith(SERVICE_EVENT_PREFIX)) {
            continue;
        }
        const parsed = parseServiceEvent(line);
        if (parsed &&
            parsed.type === shared_1.SERVICE_EVENT_TYPES.repoResult &&
            typeof parsed.trackedProjectKey === "string" &&
            (parsed.result === shared_1.SERVICE_REPO_RESULTS.success ||
                parsed.result === shared_1.SERVICE_REPO_RESULTS.noOp ||
                parsed.result === shared_1.SERVICE_REPO_RESULTS.failed)) {
            results.set(parsed.trackedProjectKey, parsed.result);
        }
    }
    return results;
}
async function logServiceEvent(event) {
    console.log(`${SERVICE_EVENT_PREFIX}${JSON.stringify(event)}`);
}
function buildRepoEventBase(entry) {
    return {
        trackedProjectKey: (0, tracked_project_1.getEntryTrackedProjectKey)(entry),
        repositoryHost: entry.repositoryHost,
        ticketTracker: entry.ticketTracker,
    };
}
function parseServiceEvent(line) {
    try {
        const payload = line.slice(SERVICE_EVENT_PREFIX.length);
        const parsed = JSON.parse(payload);
        if (typeof parsed !== "object" || parsed === null) {
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
