"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sitesCreateSubcommand = exports.SITES_CREATE_SUBCOMMAND = void 0;
const cli_1 = require("@remotion/cli");
const config_1 = require("@remotion/cli/config");
const constants_1 = require("@remotion/lambda-client/constants");
const client_1 = require("@remotion/renderer/client");
const serverless_1 = require("@remotion/serverless");
const no_react_1 = require("remotion/no-react");
const full_client_implementation_1 = require("../../../functions/full-client-implementation");
const internals_1 = require("../../../internals");
const validate_site_name_1 = require("../../../shared/validate-site-name");
const args_1 = require("../../args");
const get_aws_region_1 = require("../../get-aws-region");
const progress_bar_1 = require("../../helpers/progress-bar");
const quit_1 = require("../../helpers/quit");
const log_1 = require("../../log");
exports.SITES_CREATE_SUBCOMMAND = 'create';
const { folderExpiryOption, publicDirOption, throwIfSiteExistsOption, disableGitSourceOption, askAIOption, experimentalClientSideRenderingOption, keyboardShortcutsOption, } = client_1.BrowserSafeApis.options;
const sitesCreateSubcommand = async (args, remotionRoot, logLevel, implementation) => {
    var _a, _b, _c, _d, _e;
    const { file, reason } = cli_1.CliInternals.findEntryPoint({
        args,
        remotionRoot,
        logLevel,
        allowDirectory: false,
    });
    if (!file) {
        log_1.Log.error({ indent: false, logLevel }, 'No entry file passed.');
        log_1.Log.info({ indent: false, logLevel }, 'Pass an additional argument specifying the entry file of your Remotion project:');
        log_1.Log.info({ indent: false, logLevel });
        log_1.Log.info({ indent: false, logLevel }, `${constants_1.BINARY_NAME} lambda sites create <entry-file.ts>`);
        (0, quit_1.quit)(1);
        return;
    }
    log_1.Log.verbose({ indent: false, logLevel }, 'Entry point:', file, 'Reason:', reason);
    const desiredSiteName = (_a = args_1.parsedLambdaCli['site-name']) !== null && _a !== void 0 ? _a : undefined;
    if (desiredSiteName !== undefined) {
        (0, validate_site_name_1.validateSiteName)(desiredSiteName);
    }
    const progressBar = cli_1.CliInternals.createOverwriteableCliOutput({
        quiet: cli_1.CliInternals.quietFlagProvided(),
        cancelSignal: null,
        // No browser logs
        updatesDontOverwrite: false,
        indent: false,
        logLevel,
    });
    const multiProgress = {
        bundleProgress: {
            doneIn: null,
            progress: 0,
        },
        bucketProgress: {
            doneIn: null,
        },
        deployProgress: {
            doneIn: null,
            totalSize: null,
            sizeUploaded: 0,
            stats: null,
        },
        diffingProgress: {
            doneIn: null,
            bytesProcessed: 0,
        },
    };
    const updateProgress = (newLine) => {
        progressBar.update([
            (0, progress_bar_1.makeBundleProgress)(multiProgress.bundleProgress),
            (0, progress_bar_1.makeBucketProgress)(multiProgress.bucketProgress),
            (0, progress_bar_1.makeDiffingProgressBar)(multiProgress.diffingProgress),
            (0, progress_bar_1.makeDeployProgressBar)(multiProgress.deployProgress),
        ]
            .filter(no_react_1.NoReactInternals.truthy)
            .join('\n'), newLine);
    };
    const bucketStart = Date.now();
    const enableFolderExpiry = folderExpiryOption.getValue({
        commandLine: cli_1.CliInternals.parsedCli,
    }).value;
    const cliBucketName = (_b = args_1.parsedLambdaCli['force-bucket-name']) !== null && _b !== void 0 ? _b : null;
    const bucketName = cliBucketName !== null && cliBucketName !== void 0 ? cliBucketName : (await (0, serverless_1.internalGetOrCreateBucket)({
        region: (0, get_aws_region_1.getAwsRegion)(),
        enableFolderExpiry,
        customCredentials: null,
        providerSpecifics: implementation,
        forcePathStyle: false,
        skipPutAcl: args_1.parsedLambdaCli.privacy === 'no-acl',
        requestHandler: null,
        logLevel,
    })).bucketName;
    multiProgress.bucketProgress.doneIn = Date.now() - bucketStart;
    updateProgress(false);
    const bundleStart = Date.now();
    let uploadStart = Date.now();
    const publicDir = publicDirOption.getValue({
        commandLine: cli_1.CliInternals.parsedCli,
    }).value;
    const throwIfSiteExists = throwIfSiteExistsOption.getValue({
        commandLine: cli_1.CliInternals.parsedCli,
    }).value;
    const disableGitSource = disableGitSourceOption.getValue({
        commandLine: cli_1.CliInternals.parsedCli,
    }).value;
    const gitSource = cli_1.CliInternals.getGitSource({
        remotionRoot,
        disableGitSource,
        logLevel,
    });
    const askAIEnabled = askAIOption.getValue({
        commandLine: cli_1.CliInternals.parsedCli,
    }).value;
    const experimentalClientSideRenderingEnabled = experimentalClientSideRenderingOption.getValue({
        commandLine: cli_1.CliInternals.parsedCli,
    }).value;
    const keyboardShortcutsEnabled = keyboardShortcutsOption.getValue({
        commandLine: cli_1.CliInternals.parsedCli,
    }).value;
    const { serveUrl, siteName, stats } = await internals_1.LambdaInternals.internalDeploySite({
        entryPoint: file,
        siteName: desiredSiteName !== null && desiredSiteName !== void 0 ? desiredSiteName : implementation.randomHash(),
        bucketName,
        options: {
            publicDir,
            rootDir: remotionRoot,
            onBundleProgress: (progress) => {
                multiProgress.bundleProgress = {
                    progress,
                    doneIn: progress === 100 ? Date.now() - bundleStart : null,
                };
                if (progress === 100) {
                    uploadStart = Date.now();
                }
                updateProgress(false);
            },
            onDiffingProgress(bytes, done) {
                const previous = multiProgress.diffingProgress.bytesProcessed;
                const newBytes = bytes - previous;
                if (newBytes > 100000000 || done) {
                    multiProgress.diffingProgress = {
                        bytesProcessed: bytes,
                        doneIn: done ? Date.now() - bundleStart : null,
                    };
                    updateProgress(false);
                }
            },
            onUploadProgress: (p) => {
                multiProgress.deployProgress = {
                    sizeUploaded: p.sizeUploaded,
                    totalSize: p.totalSize,
                    doneIn: null,
                    stats: null,
                };
                updateProgress(false);
            },
            enableCaching: client_1.BrowserSafeApis.options.bundleCacheOption.getValue({
                commandLine: cli_1.CliInternals.parsedCli,
            }).value,
            webpackOverride: (_c = config_1.ConfigInternals.getWebpackOverrideFn()) !== null && _c !== void 0 ? _c : ((f) => f),
            bypassBucketNameValidation: Boolean(args_1.parsedLambdaCli['force-bucket-name']),
            askAIEnabled,
            experimentalClientSideRenderingEnabled,
            keyboardShortcutsEnabled,
        },
        region: (0, get_aws_region_1.getAwsRegion)(),
        privacy: (_d = args_1.parsedLambdaCli.privacy) !== null && _d !== void 0 ? _d : 'public',
        gitSource,
        indent: false,
        logLevel,
        throwIfSiteExists,
        providerSpecifics: implementation,
        forcePathStyle: (_e = args_1.parsedLambdaCli['force-path-style']) !== null && _e !== void 0 ? _e : false,
        fullClientSpecifics: full_client_implementation_1.awsFullClientSpecifics,
        requestHandler: null,
    });
    const uploadDuration = Date.now() - uploadStart;
    multiProgress.deployProgress = {
        sizeUploaded: 1,
        totalSize: 1,
        doneIn: uploadDuration,
        stats: {
            addedFiles: stats.uploadedFiles,
            removedFiles: stats.deletedFiles,
            untouchedFiles: stats.untouchedFiles,
        },
    };
    updateProgress(true);
    cli_1.CliInternals.printFact('info')({
        indent: false,
        left: 'Serve URL',
        logLevel,
        right: serveUrl,
        color: 'blueBright',
    });
    cli_1.CliInternals.printFact('info')({
        indent: false,
        left: 'Site name',
        logLevel,
        right: siteName,
        color: 'blueBright',
    });
    log_1.Log.info({ indent: false, logLevel });
    log_1.Log.info({ indent: false, logLevel }, cli_1.CliInternals.chalk.blueBright('ℹ️   Redeploy your site everytime you make changes to it. You can overwrite the existing site by running:'));
    log_1.Log.info({ indent: false, logLevel }, cli_1.CliInternals.chalk.blueBright(['npx remotion lambda sites create', args[0], `--site-name=${siteName}`]
        .filter(no_react_1.NoReactInternals.truthy)
        .join(' ')));
};
exports.sitesCreateSubcommand = sitesCreateSubcommand;
