"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.DownloadArtifactWriter = exports.MAX_FILE_SIZE_BYTES = void 0;
exports.uploadDownloadArtifact = uploadDownloadArtifact;
exports.uploadDownloadArtifactViaService = uploadDownloadArtifactViaService;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const mimeTypes = __importStar(require("mime-types"));
const loggingProvider_1 = require("../providers/logging/loggingProvider");
const upload_1 = require("../upload");
const env_1 = require("../env/env");
const BaseArtifactWriter_1 = require("./BaseArtifactWriter");
exports.MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024;
function sanitizeFilename(filePath) {
    return path.basename(filePath).replace(/[^a-zA-Z0-9_.-]+/g, '_');
}
class DownloadArtifactWriter extends BaseArtifactWriter_1.BaseArtifactWriter {
    constructor(workspaceId, testRunId, stepId, projectId = env_1.GCP_PROJECT) {
        super(projectId, workspaceId);
        this.testRunId = testRunId;
        this.stepId = stepId;
    }
    async uploadFile(filePath) {
        const filename = sanitizeFilename(filePath);
        const contentType = mimeTypes.lookup(filePath) || 'application/octet-stream';
        const sizeBytes = fs.statSync(filePath).size;
        if (sizeBytes > exports.MAX_FILE_SIZE_BYTES) {
            throw new Error(`File size ${sizeBytes} bytes exceeds maximum allowed size of ${exports.MAX_FILE_SIZE_BYTES} bytes`);
        }
        const fileBuffer = fs.readFileSync(filePath);
        const gcsPath = this.buildGcsPath(filename);
        const gcsUri = this.buildGcsUri(gcsPath);
        loggingProvider_1.logger.debug(`Uploading download artifact to: ${gcsUri}`);
        await this.writeToGcs(gcsPath, contentType, fileBuffer);
        return {
            downloadURI: gcsUri,
            downloadMetadata: {
                filename,
                contentType,
                sizeBytes,
            },
        };
    }
    buildGcsPath(filename) {
        const randomComponent = this.randomPathComponent();
        const basePath = `${BaseArtifactWriter_1.EXECUTION_OUTPUT_PATH_PREFIX}/${randomComponent}/downloads/${this.testRunId}/${this.stepId}/`;
        return this.truncatePathIfNeeded(basePath, filename);
    }
}
exports.DownloadArtifactWriter = DownloadArtifactWriter;
async function uploadDownloadArtifact(filePath, workspaceId, testRunId, stepId) {
    try {
        const writer = new DownloadArtifactWriter(workspaceId, testRunId, stepId);
        const result = await writer.uploadFile(filePath);
        loggingProvider_1.logger.info(`Download artifact uploaded successfully: ${result.downloadURI}`);
        return result;
    }
    catch (error) {
        loggingProvider_1.logger.warn(`Failed to upload download artifact for step ${stepId}: ${error instanceof Error ? error.message : String(error)}`);
        return undefined;
    }
}
async function uploadDownloadArtifactViaService(filePath, workspaceId, authorizationProvider) {
    try {
        const filename = sanitizeFilename(filePath);
        const contentType = mimeTypes.lookup(filePath) || 'application/octet-stream';
        const sizeBytes = fs.statSync(filePath).size;
        if (sizeBytes > exports.MAX_FILE_SIZE_BYTES) {
            throw new Error(`File size ${sizeBytes} bytes exceeds maximum allowed size of ${exports.MAX_FILE_SIZE_BYTES} bytes`);
        }
        const client = new upload_1.UploadClient({
            uploadServiceUrl: new URL(env_1.BASE_API_URL),
            authorizationProvider,
        });
        const fileUploadUri = await client.uploadCustomFile(workspaceId, filePath, undefined, undefined, filename, 'Download');
        const downloadURI = normalizeToGcsUri(fileUploadUri);
        loggingProvider_1.logger.info(`Download artifact uploaded via upload service: ${downloadURI} (${fileUploadUri})`);
        return {
            downloadURI,
            downloadMetadata: { filename, contentType, sizeBytes },
        };
    }
    catch (error) {
        loggingProvider_1.logger.warn(`Failed to upload download artifact via upload service: ${error instanceof Error ? error.message : String(error)}`);
        return undefined;
    }
}
function normalizeToGcsUri(uri) {
    return uri.startsWith('storage.googleapis.com/')
        ? `gs://${uri.slice('storage.googleapis.com/'.length)}`
        : uri;
}
