import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { getProfile } from "../config/index.js";
import { GoogleDriveClient } from "../drive/google-drive.js";
import { createTosSignedUrl, formatTosUri, uploadTosObject } from "../tos-storage.js";
function slugify(value) {
    const slug = value
        .trim()
        .toLowerCase()
        .replace(/[^a-z0-9._-]+/g, "-")
        .replace(/^-+|-+$/g, "");
    return slug || "unknown";
}
export function buildBackupTosKey(config, zipName) {
    return `backups/${slugify(config.agentName)}/${slugify(getProfile())}/${zipName}`;
}
export async function uploadBackup(options) {
    if (options.provider === "gdrive") {
        return uploadBackupToGoogleDrive(options);
    }
    return uploadBackupToTos(options);
}
export async function uploadBackupToGoogleDrive(options) {
    const drive = new GoogleDriveClient(options.config);
    const uploaded = await drive.uploadFile({
        localPath: options.localPath,
        name: options.name,
        mimeType: options.contentType,
        onProgress: (uploadedBytes) => {
            options.onProgress?.({ uploadedBytes });
        },
    });
    await drive.shareFile({
        fileId: uploaded.id,
        email: options.ownerEmail,
        role: "reader",
        sendNotification: false,
    });
    return {
        provider: "gdrive",
        location: uploaded.webViewLink ?? `https://drive.google.com/file/d/${uploaded.id}/view`,
        sizeBytes: fs.statSync(options.localPath).size,
    };
}
export async function uploadBackupToTos(options) {
    const sizeBytes = fs.statSync(options.localPath).size;
    const credentials = {
        accessKeyId: options.tos.accessKeyId,
        accessKeySecret: options.tos.accessKeySecret,
        region: options.tos.region,
        endpoint: options.tos.endpoint,
    };
    await uploadTosObject({
        filePath: options.localPath,
        bucket: options.tos.bucket,
        key: options.tos.key,
        credentials,
        contentType: options.contentType,
        checkpointDir: path.join(os.tmpdir(), ".tos-backup-checkpoints"),
        onProgress: (progress) => {
            options.onProgress?.({ uploadedBytes: progress.uploadedBytes });
        },
    });
    const signedUrl = createTosSignedUrl({
        bucket: options.tos.bucket,
        key: options.tos.key,
        credentials,
        expiresSeconds: options.tos.signedUrlExpiresSeconds,
        publicEndpoint: options.tos.publicEndpoint,
    });
    const expiresAt = new Date(Date.now() + options.tos.signedUrlExpiresSeconds * 1000).toISOString();
    return {
        provider: "tos",
        location: formatTosUri(options.tos.bucket, options.tos.key),
        signedUrl,
        key: options.tos.key,
        bucket: options.tos.bucket,
        sizeBytes,
        expiresAt,
    };
}
//# sourceMappingURL=backup-uploader.js.map