import { randomBytes } from "node:crypto";
import { spawnSync } from "node:child_process";
import open from "open";
import prompts from "prompts";
const IS_WINDOWS = process.platform === "win32";
function isGcloudInstalled() {
    const cmd = IS_WINDOWS ? "where" : "which";
    const result = spawnSync(cmd, ["gcloud"], { encoding: "utf-8" });
    return result.stdout.trim().length > 0;
}
function runGcloud(args, options) {
    const result = spawnSync("gcloud", args, {
        encoding: "utf-8",
        stdio: options?.captureOutput ? "pipe" : ["inherit", "pipe", "pipe"],
    });
    return {
        ok: result.status === 0,
        stdout: result.stdout.trim(),
        stderr: result.stderr.trim(),
    };
}
function installGcloud() {
    if (IS_WINDOWS) {
        console.log("  Installing Google Cloud SDK via winget...\n");
        const result = spawnSync("winget", ["install", "--id", "Google.CloudSDK", "--accept-source-agreements", "--accept-package-agreements"], { stdio: "inherit", timeout: 300_000 });
        if (result.status !== 0) {
            return false;
        }
        // Verify gcloud is on PATH after install
        const check = spawnSync("where", ["gcloud"], { encoding: "utf-8" });
        return check.stdout.trim().length > 0;
    }
    console.log("  Installing Google Cloud SDK via Homebrew...\n");
    const result = spawnSync("brew", ["install", "--cask", "google-cloud-sdk"], {
        stdio: "inherit",
    });
    if (result.status !== 0) {
        return false;
    }
    // Homebrew cask installs gcloud to a predictable location but the binary
    // may not be on PATH until a new shell is opened. Source the path helper
    // so subsequent spawnSync calls find it.
    const pathResult = spawnSync("bash", ["-c", "source \"$(brew --prefix)/share/google-cloud-sdk/path.bash.inc\" 2>/dev/null && which gcloud"], { encoding: "utf-8" });
    return pathResult.stdout.trim().length > 0;
}
function ensureGcloudAuth() {
    const { ok, stdout } = runGcloud(["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"], { captureOutput: true });
    if (ok && stdout.length > 0) {
        console.log(`  Already authenticated as: ${stdout.split("\n")[0]}`);
        return true;
    }
    console.log("  Launching gcloud authentication in your browser...\n");
    const authResult = spawnSync("gcloud", ["auth", "login"], {
        stdio: "inherit",
    });
    return authResult.status === 0;
}
function createProject(projectId) {
    console.log(`  Creating project: ${projectId} ...`);
    const { ok, stderr } = runGcloud(["projects", "create", projectId, "--name=VisionClaw"], { captureOutput: true });
    if (ok) {
        console.log("  Project created.");
        return true;
    }
    if (stderr.includes("already exists")) {
        console.log("  Project already exists — reusing it.");
        return true;
    }
    console.error(`  Failed to create project: ${stderr}`);
    return false;
}
function setActiveProject(projectId) {
    const { ok } = runGcloud(["config", "set", "project", projectId], { captureOutput: true });
    return ok;
}
function enableApis(projectId) {
    console.log("  Enabling Gmail, Calendar, and Drive APIs...");
    const { ok, stderr } = runGcloud([
        "services",
        "enable",
        "gmail.googleapis.com",
        "calendar-json.googleapis.com",
        "drive.googleapis.com",
        `--project=${projectId}`,
    ], { captureOutput: true });
    if (!ok) {
        console.error(`  Failed to enable APIs: ${stderr}`);
    }
    return ok;
}
/**
 * Automated Google Cloud project + OAuth credential setup.
 *
 * Automates: gcloud install, auth, project creation, API enabling, and
 * consent-screen/credential guidance. Returns the client ID and secret
 * entered by the user after creating the Desktop OAuth client in the Console.
 */
export async function runGoogleCloudSetup(agentGmail) {
    console.log("\n--- Automated Google Cloud Setup ---\n");
    // ── Step 1: ensure gcloud CLI is installed ──
    if (!isGcloudInstalled()) {
        console.log("  gcloud CLI not found.");
        const installMethod = IS_WINDOWS ? "winget" : "Homebrew";
        const installResult = (await prompts({
            type: "confirm",
            name: "install",
            message: `Install Google Cloud SDK via ${installMethod}?`,
            initial: true,
        }));
        if (!installResult.install) {
            const manualCmd = IS_WINDOWS
                ? "winget install Google.CloudSDK"
                : "brew install --cask google-cloud-sdk";
            throw new Error(`gcloud CLI is required for automatic setup. ` +
                `Install it manually (${manualCmd}) and try again.`);
        }
        if (!installGcloud()) {
            const manualCmd = IS_WINDOWS
                ? "winget install Google.CloudSDK"
                : "brew install --cask google-cloud-sdk";
            throw new Error(`Failed to install Google Cloud SDK. ` +
                `Try installing manually: ${manualCmd}`);
        }
        console.log("  Google Cloud SDK installed successfully.\n");
    }
    else {
        console.log("  gcloud CLI found.\n");
    }
    // ── Step 2: authenticate ──
    if (!ensureGcloudAuth()) {
        throw new Error("gcloud authentication failed. Please try again.");
    }
    console.log("");
    // ── Step 3: create project ──
    const suffix = randomBytes(2).toString("hex");
    const defaultProjectId = `visionclaw-${suffix}`;
    const projectResult = (await prompts({
        type: "text",
        name: "projectId",
        message: "Google Cloud project ID:",
        initial: defaultProjectId,
        validate: (v) => {
            const id = v.trim();
            if (id.length < 6 || id.length > 30) {
                return "Project ID must be 6-30 characters";
            }
            if (!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(id)) {
                return "Must start with a letter, end with letter/digit, contain only lowercase letters, digits, and hyphens";
            }
            return true;
        },
    }));
    const projectId = projectResult.projectId?.trim();
    if (!projectId) {
        throw new Error("Setup cancelled");
    }
    if (!createProject(projectId)) {
        throw new Error(`Failed to create Google Cloud project "${projectId}".`);
    }
    if (!setActiveProject(projectId)) {
        throw new Error(`Failed to set active project to "${projectId}".`);
    }
    // ── Step 4: enable APIs ──
    if (!enableApis(projectId)) {
        throw new Error("Failed to enable required Google APIs.");
    }
    console.log("  APIs enabled successfully.\n");
    // ── Step 5: configure OAuth consent screen ──
    console.log("--- OAuth Consent Screen ---\n");
    console.log("  Opening the Google Auth Platform branding page in your browser.");
    console.log("  Please complete the following steps:\n");
    console.log("    1. If prompted, click \"Get Started\" to enable the Google Auth Platform");
    console.log("    2. Set App name to \"VisionClaw\"");
    console.log(`    3. Set User support email to: ${agentGmail}`);
    console.log("    4. Set Audience to \"External\"");
    console.log(`    5. Under "Test users", add: ${agentGmail}`);
    console.log("    6. Accept defaults for everything else and save\n");
    const consentUrl = `https://console.cloud.google.com/auth/branding?project=${projectId}`;
    await open(consentUrl).catch(() => {
        console.log(`  Could not open browser. Visit: ${consentUrl}`);
    });
    const consentDone = (await prompts({
        type: "confirm",
        name: "done",
        message: "Have you finished configuring the OAuth consent screen?",
        initial: true,
    }));
    if (!consentDone.done) {
        throw new Error("OAuth consent screen must be configured before creating credentials. " +
            "Run setup again when ready.");
    }
    // ── Step 6: guide user to create Desktop OAuth client ──
    console.log("\n--- Create Desktop OAuth Client ---\n");
    console.log("  Opening the credentials page in your browser.");
    console.log("  Please complete the following steps:\n");
    console.log('    1. Click "Create OAuth client ID"');
    console.log('    2. Set Application type to "Desktop app"');
    console.log('    3. Set Name to "VisionClaw Desktop"');
    console.log('    4. Click "Create"');
    console.log("    5. Copy the Client ID and Client Secret shown in the dialog\n");
    const credentialsUrl = `https://console.cloud.google.com/apis/credentials?project=${projectId}`;
    await open(credentialsUrl).catch(() => {
        console.log(`  Could not open browser. Visit: ${credentialsUrl}`);
    });
    const clientIdResult = (await prompts({
        type: "text",
        name: "clientId",
        message: "Paste the OAuth2 Client ID:",
        validate: (v) => v.trim().length > 0 ? true : "Client ID is required",
    }));
    const clientId = clientIdResult.clientId?.trim();
    if (!clientId) {
        throw new Error("Setup cancelled");
    }
    const clientSecretResult = (await prompts({
        type: "password",
        name: "clientSecret",
        message: "Paste the OAuth2 Client Secret:",
        validate: (v) => v.trim().length > 0 ? true : "Client Secret is required",
    }));
    const clientSecret = clientSecretResult.clientSecret?.trim();
    if (!clientSecret) {
        throw new Error("Setup cancelled");
    }
    console.log("\n  Google Cloud setup complete!\n");
    return { clientId, clientSecret };
}
//# sourceMappingURL=google-cloud-setup.js.map