import { getProfile, loadConfig, loadOwnerConfig } from "./config/index.js";
import { runBackup } from "./agent/backup.js";
import { logger } from "./logger.js";
function normalizeBackupProvider(value) {
    switch (value) {
        case "gdrive":
        case "drive":
        case "google-drive":
        case "google":
            return "gdrive";
        case "tos":
            return "tos";
        default:
            throw new Error(`Unknown backup provider: ${value}. Expected gdrive or tos.`);
    }
}
function parseDurationSeconds(value) {
    const trimmed = value.trim().toLowerCase();
    const match = /^(\d+)([dhm])?$/.exec(trimmed);
    if (!match) {
        throw new Error(`Invalid --signed-url-expires value: ${value}. Use 7d, 24h, 60m, or seconds.`);
    }
    const amount = Number(match[1]);
    if (!Number.isSafeInteger(amount) || amount <= 0) {
        throw new Error(`Invalid --signed-url-expires value: ${value}. Duration must be positive.`);
    }
    const unit = match[2];
    if (unit === "d")
        return amount * 24 * 60 * 60;
    if (unit === "h")
        return amount * 60 * 60;
    if (unit === "m")
        return amount * 60;
    return amount;
}
export function parseBackupCliArgs(args) {
    const options = {};
    for (let i = 0; i < args.length; i += 1) {
        const arg = args[i];
        if (arg === "--profile") {
            i += 1;
            continue;
        }
        if (arg === "-d" ||
            arg === "--debug" ||
            arg === "-h" ||
            arg === "--help" ||
            arg === "-v" ||
            arg === "--version") {
            continue;
        }
        if (arg === "--provider") {
            const value = args[i + 1];
            if (!value)
                throw new Error("Missing value for --provider.");
            options.provider = normalizeBackupProvider(value);
            i += 1;
            continue;
        }
        if (arg === "--signed-url-expires") {
            const value = args[i + 1];
            if (!value)
                throw new Error("Missing value for --signed-url-expires.");
            options.signedUrlExpiresSeconds = parseDurationSeconds(value);
            i += 1;
            continue;
        }
        if (arg.startsWith("-")) {
            throw new Error(`Unknown backup option: ${arg}`);
        }
        throw new Error(`Unexpected backup argument: ${arg}`);
    }
    return options;
}
function shellQuote(value) {
    return `'${value.replaceAll("'", "'\\''")}'`;
}
function getRestoreSource(result) {
    if (result.provider === "tos")
        return result.signedUrl;
    return result.location;
}
export function formatRestoreCommand(result) {
    const source = getRestoreSource(result);
    if (!source)
        return undefined;
    return `visionclaw restore ${shellQuote(source)} --force`;
}
export function formatBackupResult(result) {
    const restoreCommand = formatRestoreCommand(result);
    if (result.provider === "tos") {
        const lines = [`Backup internal location:\n${result.location}`];
        if (result.signedUrl) {
            const expires = result.expiresAt ? ` expires at ${result.expiresAt}` : "";
            lines.push(`Signed download URL${expires}:\n${result.signedUrl}`);
        }
        if (restoreCommand) {
            lines.push(`Restore command:\n${restoreCommand}`);
        }
        return lines.join("\n\n");
    }
    return restoreCommand ? `${result.location}\n\nRestore command:\n${restoreCommand}` : result.location;
}
export async function runBackupCli(args = process.argv.slice(2)) {
    const config = loadConfig();
    const ownerConfig = loadOwnerConfig();
    const options = parseBackupCliArgs(args);
    logger.system(`Creating backup for profile "${getProfile()}"...`);
    const result = await runBackup(config, ownerConfig.ownerEmail, options);
    logger.system(`Backup complete: ${formatBackupResult(result)}`);
}
//# sourceMappingURL=backup.js.map