"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VercelEnvironmentProvider = void 0;
const child_process_1 = require("child_process");
// `vercel` ships as `vercel.cmd` when installed via npm on Windows. The
// stock `child_process.spawn` does not consult PATHEXT, so we use the
// cross-platform wrapper for the spawn paths. `execSync` already routes
// through `cmd.exe` on Windows, which DOES consult PATHEXT, so it stays.
const cross_platform_spawn_js_1 = require("../../../utils/cross-platform-spawn.js");
const EnvironmentProvider_1 = require("../EnvironmentProvider");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../../ui");
const chalk_1 = __importDefault(require("chalk"));
const analytics_1 = require("../../../utils/analytics");
class VercelEnvironmentProvider extends EnvironmentProvider_1.EnvironmentProvider {
    name = 'Vercel';
    environments = ['production', 'preview', 'development'];
    constructor(options) {
        super(options);
    }
    // eslint-disable-next-line @typescript-eslint/require-await
    async detect() {
        const cliInstalled = this.hasVercelCli();
        const projectLinked = this.isProjectLinked();
        const authenticated = cliInstalled && projectLinked && this.isAuthenticated();
        const vercelDetected = cliInstalled && projectLinked && authenticated;
        // Report detection status as event properties (not session-global tags)
        analytics_1.analytics.wizardCapture('vercel detection', {
            'vercel detected': vercelDetected,
            'vercel cli installed': cliInstalled,
            'vercel project linked': projectLinked,
            'vercel authenticated': authenticated,
        });
        return vercelDetected;
    }
    hasDotVercelDir() {
        const dotVercelDir = path.join(this.options.installDir, '.vercel');
        return fs.existsSync(dotVercelDir);
    }
    hasVercelCli() {
        try {
            (0, child_process_1.execSync)('vercel --version', { stdio: 'ignore' });
            return true;
        }
        catch {
            return false;
        }
    }
    isProjectLinked() {
        return fs.existsSync(path.join(this.options.installDir, '.vercel', 'project.json'));
    }
    isAuthenticated() {
        const result = (0, cross_platform_spawn_js_1.spawnSync)('vercel', ['whoami'], {
            encoding: 'utf-8',
            stdio: ['pipe', 'pipe', 'pipe'], // suppress prompts
            env: {
                ...process.env,
                FORCE_COLOR: '0', // avoid ANSI formatting
                CI: '1', // hint to CLI that it's a non-interactive env
            },
        });
        const output = (String(result.stdout) + String(result.stderr)).toLowerCase();
        return !(output.includes('log in to vercel') ||
            output.includes('vercel login') ||
            result.status !== 0);
    }
    async uploadEnvironmentVariable(key, value, environment) {
        await new Promise((resolve, reject) => {
            const proc = (0, cross_platform_spawn_js_1.spawn)('vercel', ['env', 'add', key, environment], {
                stdio: ['pipe', 'pipe', 'pipe'],
            });
            let stderr = '';
            proc.stderr.on('data', (data) => {
                stderr += data.toString();
            });
            proc.stdin.write(value);
            proc.stdin.end();
            proc.on('close', (code) => {
                if (stderr.includes('already exists') ||
                    stderr.includes('already been added') ||
                    stderr.includes('vercel env rm')) {
                    reject(new Error(`❌ Environment variable ${chalk_1.default.cyan(key)} already exists in ${this.name}. Please upload it manually.`));
                }
                else if (code === 0) {
                    resolve();
                }
                else {
                    reject(new Error(`❌ Failed to upload environment variable ${chalk_1.default.cyan(key)} to ${this.name}. Please upload it manually.`));
                }
            });
        });
    }
    async uploadEnvVars(vars) {
        const results = {};
        for (const [key, value] of Object.entries(vars)) {
            const spinner = (0, ui_1.getUI)().spinner();
            spinner.start(`Uploading ${chalk_1.default.cyan(key)} to ${this.name}...`);
            await Promise.all(this.environments.map((environment) => this.uploadEnvironmentVariable(key, value, environment)))
                .then(() => {
                spinner.stop(`✅ Uploaded ${chalk_1.default.cyan(key)} to ${this.name}`);
                results[key] = true;
            })
                .catch((err) => {
                spinner.stop(err instanceof Error
                    ? err.message
                    : `❌ Failed to upload environment variables to ${this.name}. Please upload it manually.`);
                results[key] = false;
            });
        }
        return results;
    }
}
exports.VercelEnvironmentProvider = VercelEnvironmentProvider;
