"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.runGovernanceUploadForWorkspace = runGovernanceUploadForWorkspace;
const path = __importStar(require("node:path"));
const config_1 = require("../config");
const operationalLogging_1 = require("../operationalLogging");
const governanceUploadPayload_1 = require("./governanceUploadPayload");
const governanceUploadClient_1 = require("./governanceUploadClient");
const cloudConnection_1 = require("./cloudConnection");
async function runGovernanceUploadForWorkspace(input) {
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', 'Preparing governance upload payload from local validation artifacts.');
    const projectConfig = await (0, config_1.readProjectConfig)(input.workspaceRoot);
    if (projectConfig.invalidJson && (!input.serverUrl || !input.token)) {
        throw new Error(projectConfig.errorMessage ??
            'ArchPilot project config is invalid. Please fix .archpilot/config.json.');
    }
    const projectIdentityLoaded = await (0, config_1.readProjectIdentity)(input.workspaceRoot);
    if (projectIdentityLoaded.invalidJson) {
        throw new Error(projectIdentityLoaded.errorMessage ??
            'ArchPilot project identity config is invalid. Please fix .archpilot/project.json.');
    }
    const payloadResult = await (0, governanceUploadPayload_1.buildGovernanceUploadPayloadForWorkspace)({
        workspaceRoot: input.workspaceRoot,
        ...(projectIdentityLoaded.identity
            ? { projectIdentity: projectIdentityLoaded.identity }
            : {}),
        archpilotVersion: input.archpilotVersion,
        environment: input.environment,
    });
    if (payloadResult.kind === 'missing-artifact' || payloadResult.kind === 'invalid-artifact') {
        throw new Error(payloadResult.message ?? 'Unable to build governance upload payload.');
    }
    const serverUrl = (0, cloudConnection_1.resolveArchPilotCloudServer)({
        ...(input.serverUrl ?? projectConfig.config?.cloud?.server
            ? { explicitServerUrl: input.serverUrl ?? projectConfig.config?.cloud?.server }
            : {}),
        environment: input.environment ?? process.env,
    }).apiBaseUrl;
    const token = input.token ?? projectConfig.config?.cloud?.token;
    if (!token) {
        throw new Error('Governance upload requires an API token. Provide --token or configure ArchPilot Cloud in .archpilot/config.json / Inspector.');
    }
    const payload = payloadResult.payload;
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', `Uploading governance snapshot to ${serverUrl}.`);
    const response = await (0, governanceUploadClient_1.uploadGovernanceSnapshot)({
        serverUrl,
        token,
        payload,
    });
    if (!input.serverUrl && !input.token && projectConfig.config?.cloud) {
        await (0, config_1.writeProjectConfig)(input.workspaceRoot, {
            ...projectConfig.config,
            cloud: {
                ...projectConfig.config.cloud,
                lastUploadAt: new Date().toISOString(),
            },
        });
    }
    return {
        repository: payload.repository.repositoryId || path.basename(input.workspaceRoot),
        commitSha: payload.snapshot.commitSha || 'unknown commit',
        totalFindings: payload.snapshot.findingsCount.total,
        errors: payload.snapshot.findingsCount.error,
        warnings: payload.snapshot.findingsCount.warning,
        architectureHealth: payload.snapshot.architectureScore,
        endpoint: response.endpoint,
        statusCode: response.statusCode,
    };
}
//# sourceMappingURL=runGovernanceUpload.js.map