#!/usr/bin/env node
import { PATScope, applyCommand, commonArgs, createCommand, deleteCommand, executionsCommand, fetchAll, fetchLatestToken, fetchUserInfo, formatArgs, generateCommand, getCommand, getCommand$1, initOAuth2Client, initOperatorClient, listCommand as listCommand$1, listCommand$1 as listCommand$6, listCommand$2 as listCommand$7, listCommand$3 as listCommand, loadAccessToken, loadConfig, loadWorkspaceId, parseFormat, printWithFormat, readPackageJson, readPlatformConfig, removeCommand, resumeCommand, showCommand, startCommand, tokenCommand, withCommonArgs, writePlatformConfig } from "../resume-Bk4u_qL4.mjs";
import "../job-BGBMNqRW.mjs";
import { register } from "node:module";
import { defineCommand, runCommand, runMain } from "citty";
import { z } from "zod";
import * as crypto from "node:crypto";
import ml from "multiline-ts";
import { consola as consola$1 } from "consola";
import { generateCodeVerifier } from "@badgateway/oauth2-client";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { Code, ConnectError } from "@connectrpc/connect";
import chalk from "chalk";
import { spawnSync } from "node:child_process";
import * as http from "node:http";
import open from "open";

//#region src/cli/init.ts
const detectPackageManager = () => {
	const availablePMs = [
		"npm",
		"yarn",
		"pnpm"
	];
	const userAgent = process.env.npm_config_user_agent;
	if (!userAgent) return;
	const [name] = userAgent.split("/");
	if (!availablePMs.includes(name)) return;
	return name;
};
const initCommand = defineCommand({
	meta: {
		name: "init",
		description: "Initialize a new project using create-sdk"
	},
	args: {
		...commonArgs,
		name: {
			type: "positional",
			description: "Project name",
			required: false
		},
		template: {
			type: "string",
			description: "Template name",
			required: false,
			alias: "t"
		}
	},
	run: withCommonArgs(async (args) => {
		const packageJson$1 = await readPackageJson();
		const version = packageJson$1.version && packageJson$1.version !== "0.0.0" ? packageJson$1.version : "latest";
		let packageManager = detectPackageManager();
		if (!packageManager) {
			consola$1.warn("⚠️ Could not detect package manager, defaulting to npm");
			packageManager = "npm";
		}
		const initArgs = [
			"create",
			`@tailor-platform/sdk@${version}`,
			...args.name ? [args.name] : [],
			...packageManager === "npm" ? ["--"] : [],
			...args.template ? ["--template", args.template] : []
		];
		consola$1.log(`Running: ${packageManager} ${initArgs.join(" ")}`);
		spawnSync(packageManager, initArgs, { stdio: "inherit" });
	})
});

//#endregion
//#region src/cli/login.ts
const redirectPort = 8085;
const redirectUri = `http://localhost:${redirectPort}/callback`;
function randomState() {
	return crypto.randomBytes(32).toString("base64url");
}
const startAuthServer = async () => {
	const client = initOAuth2Client();
	const state = randomState();
	const codeVerifier = await generateCodeVerifier();
	return new Promise((resolve, reject) => {
		const server = http.createServer(async (req, res) => {
			try {
				if (!req.url?.startsWith("/callback")) throw new Error("Invalid callback URL");
				const tokens = await client.authorizationCode.getTokenFromCodeRedirect(`http://${req.headers.host}${req.url}`, {
					redirectUri,
					state,
					codeVerifier
				});
				const userInfo = await fetchUserInfo(tokens.accessToken);
				const pfConfig = readPlatformConfig();
				pfConfig.users = {
					...pfConfig.users,
					[userInfo.email]: {
						access_token: tokens.accessToken,
						refresh_token: tokens.refreshToken,
						token_expires_at: new Date(tokens.expiresAt).toISOString()
					}
				};
				pfConfig.current_user = userInfo.email;
				writePlatformConfig(pfConfig);
				res.writeHead(200, { "Content-Type": "application/json" });
				res.end(JSON.stringify({
					status: "ok",
					message: "Successfully authenticated. Please close this window."
				}));
				resolve();
			} catch (error) {
				res.writeHead(401);
				res.end("Authentication failed");
				reject(error);
			} finally {
				server.close();
			}
		});
		const timeout = setTimeout(() => {
			server.close();
			reject(/* @__PURE__ */ new Error("Login timeout exceeded"));
		}, 300 * 1e3);
		server.on("close", () => {
			clearTimeout(timeout);
		});
		server.on("error", (error) => {
			reject(error);
		});
		server.listen(redirectPort, async () => {
			const authorizeUri = await client.authorizationCode.getAuthorizeUri({
				redirectUri,
				state,
				codeVerifier
			});
			consola$1.info(`Opening browser for login:\n\n${authorizeUri}\n`);
			try {
				await open(authorizeUri);
			} catch {
				consola$1.warn("Failed to open browser automatically. Please open the URL above manually.");
			}
		});
	});
};
const loginCommand = defineCommand({
	meta: {
		name: "login",
		description: "Login to Tailor Platform"
	},
	args: commonArgs,
	run: withCommonArgs(async () => {
		await startAuthServer();
		consola$1.success("Successfully logged in to Tailor Platform.");
	})
});

//#endregion
//#region src/cli/logout.ts
const logoutCommand = defineCommand({
	meta: {
		name: "logout",
		description: "Logout from Tailor Platform"
	},
	args: commonArgs,
	run: withCommonArgs(async () => {
		const pfConfig = readPlatformConfig();
		const tokens = pfConfig.current_user ? pfConfig.users[pfConfig.current_user] : void 0;
		if (!tokens) {
			consola$1.warn("You are not logged in.");
			return;
		}
		initOAuth2Client().revoke({
			accessToken: tokens.access_token,
			refreshToken: tokens.refresh_token,
			expiresAt: Date.parse(tokens.token_expires_at)
		}, "refresh_token");
		delete pfConfig.users[pfConfig.current_user];
		pfConfig.current_user = null;
		writePlatformConfig(pfConfig);
		consola$1.success("Successfully logged out from Tailor Platform.");
	})
});

//#endregion
//#region src/cli/machineuser/index.ts
const machineuserCommand = defineCommand({
	meta: {
		name: "machineuser",
		description: "Manage machine users"
	},
	subCommands: {
		list: listCommand$7,
		token: tokenCommand
	},
	async run() {
		await runCommand(listCommand$7, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/oauth2client/index.ts
const oauth2clientCommand = defineCommand({
	meta: {
		name: "oauth2client",
		description: "Manage OAuth2 clients"
	},
	subCommands: {
		get: getCommand$1,
		list: listCommand$6
	},
	async run() {
		await runCommand(listCommand$6, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/profile/create.ts
const createCommand$3 = defineCommand({
	meta: {
		name: "create",
		description: "Create new profile"
	},
	args: {
		...commonArgs,
		...formatArgs,
		name: {
			type: "positional",
			description: "Profile name",
			required: true
		},
		user: {
			type: "string",
			description: "User email",
			required: true,
			alias: "u"
		},
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			required: true,
			alias: "w"
		}
	},
	run: withCommonArgs(async (args) => {
		const format = parseFormat(args.format);
		const config = readPlatformConfig();
		if (config.profiles[args.name]) throw new Error(`Profile "${args.name}" already exists.`);
		const token = await fetchLatestToken(config, args.user);
		const client = await initOperatorClient(token);
		if (!(await fetchAll(async (pageToken) => {
			const { workspaces, nextPageToken } = await client.listWorkspaces({ pageToken });
			return [workspaces, nextPageToken];
		})).find((ws) => ws.id === args["workspace-id"])) throw new Error(`Workspace "${args["workspace-id"]}" not found.`);
		config.profiles[args.name] = {
			user: args.user,
			workspace_id: args["workspace-id"]
		};
		writePlatformConfig(config);
		if (format === "table") consola$1.success(`Profile "${args.name}" created successfully.`);
		const profileInfo = {
			name: args.name,
			user: args.user,
			workspaceId: args["workspace-id"]
		};
		printWithFormat(profileInfo, format);
	})
});

//#endregion
//#region src/cli/profile/delete.ts
const deleteCommand$3 = defineCommand({
	meta: {
		name: "delete",
		description: "Delete profile"
	},
	args: {
		...commonArgs,
		name: {
			type: "positional",
			description: "Profile name",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.profiles[args.name]) throw new Error(`Profile "${args.name}" not found.`);
		delete config.profiles[args.name];
		writePlatformConfig(config);
		consola$1.success(`Profile "${args.name}" deleted successfully.`);
	})
});

//#endregion
//#region src/cli/profile/list.ts
const listCommand$5 = defineCommand({
	meta: {
		name: "list",
		description: "List all profiles"
	},
	args: {
		...commonArgs,
		...formatArgs
	},
	run: withCommonArgs(async (args) => {
		const format = parseFormat(args.format);
		const config = readPlatformConfig();
		const profiles = Object.entries(config.profiles);
		if (profiles.length === 0) {
			consola$1.info(ml`
        No profiles found.
        Please create a profile first using 'tailor-sdk profile create' command.
      `);
			return;
		}
		const profileInfos = profiles.map(([name, profile]) => ({
			name,
			user: profile.user,
			workspaceId: profile.workspace_id
		}));
		printWithFormat(profileInfos, format);
	})
});

//#endregion
//#region src/cli/profile/update.ts
const updateCommand$1 = defineCommand({
	meta: {
		name: "update",
		description: "Update profile properties"
	},
	args: {
		...commonArgs,
		...formatArgs,
		name: {
			type: "positional",
			description: "Profile name",
			required: true
		},
		user: {
			type: "string",
			description: "New user email",
			alias: "u"
		},
		"workspace-id": {
			type: "string",
			description: "New workspace ID",
			alias: "w"
		}
	},
	run: withCommonArgs(async (args) => {
		const format = parseFormat(args.format);
		const config = readPlatformConfig();
		if (!config.profiles[args.name]) throw new Error(`Profile "${args.name}" not found.`);
		if (!args.user && !args["workspace-id"]) throw new Error("Please provide at least one property to update.");
		const profile = config.profiles[args.name];
		const oldUser = profile.user;
		const newUser = args.user || oldUser;
		const oldWorkspaceId = profile.workspace_id;
		const newWorkspaceId = args["workspace-id"] || oldWorkspaceId;
		const token = await fetchLatestToken(config, newUser);
		const client = await initOperatorClient(token);
		if (!(await fetchAll(async (pageToken) => {
			const { workspaces, nextPageToken } = await client.listWorkspaces({ pageToken });
			return [workspaces, nextPageToken];
		})).find((ws) => ws.id === newWorkspaceId)) throw new Error(`Workspace "${newWorkspaceId}" not found.`);
		profile.user = newUser;
		profile.workspace_id = newWorkspaceId;
		writePlatformConfig(config);
		if (format === "table") consola$1.success(`Profile "${args.name}" updated successfully`);
		const profileInfo = {
			name: args.name,
			user: newUser,
			workspaceId: newWorkspaceId
		};
		printWithFormat(profileInfo, format);
	})
});

//#endregion
//#region src/cli/profile/index.ts
const profileCommand = defineCommand({
	meta: {
		name: "profile",
		description: "Manage workspace profiles (user + workspace combinations)"
	},
	subCommands: {
		create: createCommand$3,
		delete: deleteCommand$3,
		list: listCommand$5,
		update: updateCommand$1
	},
	async run() {
		await runCommand(listCommand$5, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/secret/create.ts
const createSecretCommand = defineCommand({
	meta: {
		name: "create",
		description: "Create a secret in a vault"
	},
	args: {
		...commonArgs,
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		},
		"vault-name": {
			type: "string",
			description: "Vault name",
			required: true
		},
		name: {
			type: "string",
			description: "Secret name",
			required: true
		},
		value: {
			type: "string",
			description: "Secret value",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const accessToken = await loadAccessToken({
			useProfile: true,
			profile: args.profile
		});
		const client = await initOperatorClient(accessToken);
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		try {
			await client.createSecretManagerSecret({
				workspaceId,
				secretmanagerVaultName: args["vault-name"],
				secretmanagerSecretName: args.name,
				secretmanagerSecretValue: args.value
			});
		} catch (error) {
			if (error instanceof ConnectError) {
				if (error.code === Code.NotFound) throw new Error(`Vault "${args["vault-name"]}" not found.`);
				if (error.code === Code.AlreadyExists) throw new Error(`Secret "${args.name}" already exists.`);
			}
			throw error;
		}
		consola$1.success(`Secret: ${args.name} created in vault: ${args["vault-name"]}`);
	})
});

//#endregion
//#region src/cli/secret/delete.ts
const deleteSecretCommand = defineCommand({
	meta: {
		name: "delete",
		description: "Delete a secret in a vault"
	},
	args: {
		...commonArgs,
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		},
		"vault-name": {
			type: "string",
			description: "Vault name",
			required: true
		},
		name: {
			type: "string",
			description: "Secret name",
			required: true
		},
		yes: {
			type: "boolean",
			description: "Skip confirmation prompt",
			alias: "y",
			default: false
		}
	},
	run: withCommonArgs(async (args) => {
		const accessToken = await loadAccessToken({
			useProfile: true,
			profile: args.profile
		});
		const client = await initOperatorClient(accessToken);
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		if (!args.yes) {
			if (await consola$1.prompt(`Enter the secret name to confirm deletion ("${args.name}"): `, { type: "text" }) !== args.name) {
				consola$1.info("Secret deletion cancelled.");
				return;
			}
		}
		try {
			await client.deleteSecretManagerSecret({
				workspaceId,
				secretmanagerVaultName: args["vault-name"],
				secretmanagerSecretName: args.name
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Secret "${args.name}" not found in vault "${args["vault-name"]}".`);
			throw error;
		}
		consola$1.success(`Secret: ${args.name} deleted from vault: ${args["vault-name"]}`);
	})
});

//#endregion
//#region src/cli/secret/list.ts
function secretInfo(secret) {
	return {
		name: secret.name,
		createdAt: secret.createTime ? timestampDate(secret.createTime).toISOString() : "N/A",
		updatedAt: secret.updateTime ? timestampDate(secret.updateTime).toISOString() : "N/A"
	};
}
async function secretList(options) {
	const accessToken = await loadAccessToken({
		useProfile: true,
		profile: options.profile
	});
	const client = await initOperatorClient(accessToken);
	const workspaceId = loadWorkspaceId({
		workspaceId: options.workspaceId,
		profile: options.profile
	});
	return (await fetchAll(async (pageToken) => {
		const { secrets, nextPageToken } = await client.listSecretManagerSecrets({
			workspaceId,
			secretmanagerVaultName: options.vaultName,
			pageToken
		});
		return [secrets, nextPageToken];
	})).map(secretInfo);
}
const listSecretCommand = defineCommand({
	meta: {
		name: "list",
		description: "List secrets in a vault"
	},
	args: {
		...commonArgs,
		...formatArgs,
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		},
		"vault-name": {
			type: "string",
			description: "Vault name",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const format = parseFormat(args.format);
		try {
			const secrets = await secretList({
				workspaceId: args["workspace-id"],
				profile: args.profile,
				vaultName: args["vault-name"]
			});
			printWithFormat(secrets, format);
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Vault "${args["vault-name"]}" not found.`);
			throw error;
		}
	})
});

//#endregion
//#region src/cli/secret/update.ts
const updateSecretCommand = defineCommand({
	meta: {
		name: "update",
		description: "Update a secret in a vault"
	},
	args: {
		...commonArgs,
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		},
		"vault-name": {
			type: "string",
			description: "Vault name",
			required: true
		},
		name: {
			type: "string",
			description: "Secret name",
			required: true
		},
		value: {
			type: "string",
			description: "Secret value",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const accessToken = await loadAccessToken({
			useProfile: true,
			profile: args.profile
		});
		const client = await initOperatorClient(accessToken);
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		try {
			await client.updateSecretManagerSecret({
				workspaceId,
				secretmanagerVaultName: args["vault-name"],
				secretmanagerSecretName: args.name,
				secretmanagerSecretValue: args.value
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Secret "${args.name}" not found in vault "${args["vault-name"]}".`);
			throw error;
		}
		consola$1.success(`Secret: ${args.name} updated in vault: ${args["vault-name"]}`);
	})
});

//#endregion
//#region src/cli/secret/vault/create.ts
const createCommand$2 = defineCommand({
	meta: {
		name: "create",
		description: "Create a Secret Manager vault"
	},
	args: {
		...commonArgs,
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		},
		name: {
			type: "string",
			description: "Vault name",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const accessToken = await loadAccessToken({
			useProfile: true,
			profile: args.profile
		});
		const client = await initOperatorClient(accessToken);
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		try {
			await client.createSecretManagerVault({
				workspaceId,
				secretmanagerVaultName: args.name
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.AlreadyExists) throw new Error(`Vault "${args.name}" already exists.`);
			throw error;
		}
		consola$1.success(`Vault: ${args.name} created`);
	})
});

//#endregion
//#region src/cli/secret/vault/delete.ts
const deleteCommand$2 = defineCommand({
	meta: {
		name: "delete",
		description: "Delete a Secret Manager vault"
	},
	args: {
		...commonArgs,
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		},
		name: {
			type: "string",
			description: "Vault name",
			required: true
		},
		yes: {
			type: "boolean",
			description: "Skip confirmation prompt",
			alias: "y",
			default: false
		}
	},
	run: withCommonArgs(async (args) => {
		const accessToken = await loadAccessToken({
			useProfile: true,
			profile: args.profile
		});
		const client = await initOperatorClient(accessToken);
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		if (!args.yes) {
			if (await consola$1.prompt(`Enter the vault name to confirm deletion ("${args.name}"): `, { type: "text" }) !== args.name) {
				consola$1.info("Vault deletion cancelled.");
				return;
			}
		}
		try {
			await client.deleteSecretManagerVault({
				workspaceId,
				secretmanagerVaultName: args.name
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Vault "${args.name}" not found.`);
			throw error;
		}
		consola$1.success(`Vault: ${args.name} deleted`);
	})
});

//#endregion
//#region src/cli/secret/vault/list.ts
function vaultInfo(vault) {
	return {
		name: vault.name,
		createdAt: vault.createTime ? timestampDate(vault.createTime).toISOString() : "N/A",
		updatedAt: vault.updateTime ? timestampDate(vault.updateTime).toISOString() : "N/A"
	};
}
async function vaultList(options) {
	const accessToken = await loadAccessToken({
		useProfile: true,
		profile: options?.profile
	});
	const client = await initOperatorClient(accessToken);
	const workspaceId = loadWorkspaceId({
		workspaceId: options?.workspaceId,
		profile: options?.profile
	});
	return (await fetchAll(async (pageToken) => {
		const { vaults, nextPageToken } = await client.listSecretManagerVaults({
			workspaceId,
			pageToken
		});
		return [vaults, nextPageToken];
	})).map(vaultInfo);
}
const listCommand$4 = defineCommand({
	meta: {
		name: "list",
		description: "List Secret Manager vaults"
	},
	args: {
		...commonArgs,
		...formatArgs,
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		}
	},
	run: withCommonArgs(async (args) => {
		const format = parseFormat(args.format);
		const vaults = await vaultList({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		printWithFormat(vaults, format);
	})
});

//#endregion
//#region src/cli/secret/vault/index.ts
const vaultCommand = defineCommand({
	meta: {
		name: "vault",
		description: "Manage Secret Manager vaults"
	},
	subCommands: {
		create: createCommand$2,
		delete: deleteCommand$2,
		list: listCommand$4
	},
	async run() {
		await runCommand(listCommand$4, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/secret/index.ts
const secretCommand = defineCommand({
	meta: {
		name: "secret",
		description: "Manage secrets and vaults"
	},
	subCommands: {
		create: createSecretCommand,
		delete: deleteSecretCommand,
		list: listSecretCommand,
		update: updateSecretCommand,
		vault: vaultCommand
	},
	async run() {
		await runCommand(vaultCommand, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/tailordb/truncate.ts
async function truncateSingleType(options, client) {
	await client.truncateTailorDBType({
		workspaceId: options.workspaceId,
		namespaceName: options.namespaceName,
		tailordbTypeName: options.typeName
	});
	consola$1.success(`Truncated type "${options.typeName}" in namespace "${options.namespaceName}"`);
}
async function truncateNamespace(workspaceId, namespaceName, client) {
	await client.truncateTailorDBTypes({
		workspaceId,
		namespaceName
	});
	consola$1.success(`Truncated all types in namespace "${namespaceName}"`);
}
async function getAllNamespaces(configPath) {
	const { config } = await loadConfig(configPath);
	const namespaces = /* @__PURE__ */ new Set();
	if (config.db) for (const [namespaceName] of Object.entries(config.db)) namespaces.add(namespaceName);
	return Array.from(namespaces);
}
async function getTypeNamespace(workspaceId, typeName, client, configPath) {
	const namespaces = await getAllNamespaces(configPath);
	for (const namespace of namespaces) try {
		const { tailordbTypes } = await client.listTailorDBTypes({
			workspaceId,
			namespaceName: namespace
		});
		if (tailordbTypes.some((type) => type.name === typeName)) return namespace;
	} catch {
		continue;
	}
	return null;
}
async function truncate(options) {
	const accessToken = await loadAccessToken({
		useProfile: true,
		profile: options?.profile
	});
	const client = await initOperatorClient(accessToken);
	const workspaceId = loadWorkspaceId({
		workspaceId: options?.workspaceId,
		profile: options?.profile
	});
	const hasTypes = options?.types && options.types.length > 0;
	const hasNamespace = !!options?.namespace;
	const hasAll = !!options?.all;
	if ([
		hasTypes,
		hasNamespace,
		hasAll
	].filter(Boolean).length > 1) throw new Error("Cannot specify multiple options: choose one of --all, --namespace, or type names");
	if (!hasTypes && !hasNamespace && !hasAll) throw new Error("Please specify one of: --all, --namespace <name>, or type names");
	const namespaces = await getAllNamespaces(options?.configPath);
	if (hasAll) {
		if (namespaces.length === 0) {
			consola$1.warn("No namespaces found in config file.");
			return;
		}
		if (!options?.yes) {
			const namespaceList = namespaces.join(", ");
			if (!await consola$1.prompt(`This will truncate ALL tables in the following namespaces: ${namespaceList}. Continue? (yes/no)`, {
				type: "confirm",
				initial: false
			})) {
				consola$1.info("Truncate cancelled.");
				return;
			}
		}
		for (const namespace of namespaces) await truncateNamespace(workspaceId, namespace, client);
		consola$1.success("Truncated all tables in all namespaces");
		return;
	}
	if (hasNamespace && options?.namespace) {
		const namespace = options.namespace;
		if (!namespaces.includes(namespace)) throw new Error(`Namespace "${namespace}" not found in config. Available namespaces: ${namespaces.join(", ")}`);
		if (!options.yes) {
			if (!await consola$1.prompt(`This will truncate ALL tables in namespace "${namespace}". Continue? (yes/no)`, {
				type: "confirm",
				initial: false
			})) {
				consola$1.info("Truncate cancelled.");
				return;
			}
		}
		await truncateNamespace(workspaceId, namespace, client);
		return;
	}
	if (hasTypes && options?.types) {
		const typeNames = options.types;
		const typeNamespaceMap = /* @__PURE__ */ new Map();
		const notFoundTypes = [];
		for (const typeName of typeNames) {
			const namespace = await getTypeNamespace(workspaceId, typeName, client, options.configPath);
			if (namespace) typeNamespaceMap.set(typeName, namespace);
			else notFoundTypes.push(typeName);
		}
		if (notFoundTypes.length > 0) throw new Error(`The following types were not found in any namespace: ${notFoundTypes.join(", ")}`);
		if (!options.yes) {
			const typeList = typeNames.join(", ");
			if (!await consola$1.prompt(`This will truncate the following types: ${typeList}. Continue? (yes/no)`, {
				type: "confirm",
				initial: false
			})) {
				consola$1.info("Truncate cancelled.");
				return;
			}
		}
		for (const typeName of typeNames) {
			const namespace = typeNamespaceMap.get(typeName);
			if (!namespace) continue;
			await truncateSingleType({
				workspaceId,
				namespaceName: namespace,
				typeName
			}, client);
		}
	}
}
const truncateCommand = defineCommand({
	meta: {
		name: "truncate",
		description: "Truncate TailorDB tables"
	},
	args: {
		...commonArgs,
		types: {
			type: "positional",
			description: "Type names to truncate (space-separated)",
			required: false
		},
		all: {
			type: "boolean",
			description: "Truncate all tables in all namespaces",
			default: false,
			alias: "a"
		},
		namespace: {
			type: "string",
			description: "Truncate all tables in specified namespace",
			alias: "n"
		},
		yes: {
			type: "boolean",
			description: "Skip confirmation prompt",
			alias: "y",
			default: false
		},
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			alias: "w"
		},
		profile: {
			type: "string",
			description: "Workspace profile",
			alias: "p"
		},
		config: {
			type: "string",
			description: "Path to tailor config file",
			default: "tailor.config.ts",
			alias: "c"
		}
	},
	run: withCommonArgs(async (args) => {
		await truncate({
			workspaceId: args["workspace-id"],
			profile: args.profile,
			configPath: args.config,
			all: args.all,
			namespace: args.namespace,
			types: args.types ? args.types.split(/\s+/).filter(Boolean) : void 0,
			yes: args.yes
		});
	})
});

//#endregion
//#region src/cli/tailordb/index.ts
const tailordbCommand = defineCommand({
	meta: {
		name: "tailordb",
		description: "Manage TailorDB tables and data"
	},
	subCommands: { truncate: truncateCommand }
});

//#endregion
//#region src/cli/user/current.ts
const currentCommand = defineCommand({
	meta: {
		name: "current",
		description: "Show current user"
	},
	args: commonArgs,
	run: withCommonArgs(async () => {
		const config = readPlatformConfig();
		if (!config.current_user) {
			consola$1.warn(ml`
        Current user not set.
        Please login first using 'tailor-sdk login' command to register a user.
      `);
			return;
		}
		if (!config.users[config.current_user]) throw new Error(ml`
        Current user '${config.current_user}' not found in registered users.
        Please login again using 'tailor-sdk login' command to register the user.
      `);
		console.log(config.current_user);
	})
});

//#endregion
//#region src/cli/user/list.ts
const listCommand$2 = defineCommand({
	meta: {
		name: "list",
		description: "List all users"
	},
	args: {
		...commonArgs,
		...formatArgs
	},
	run: withCommonArgs(async (args) => {
		const format = parseFormat(args.format);
		const config = readPlatformConfig();
		const users = Object.keys(config.users);
		if (users.length === 0) {
			consola$1.info(ml`
        No users found.
        Please login first using 'tailor-sdk login' command to register a user.
      `);
			return;
		}
		switch (format) {
			case "table":
				users.forEach((user) => {
					if (user === config.current_user) console.log(chalk.green.bold(`${user} (current)`));
					else console.log(user);
				});
				break;
			case "json":
				console.log(JSON.stringify(users));
				break;
			default: throw new Error(`Format "${format}" is invalid.`);
		}
	})
});

//#endregion
//#region src/cli/user/pat/transform.ts
const patFormatSchema = z.enum(["text", "json"]);
const patFormatArgs = { format: {
	type: "string",
	description: `Output format (${patFormatSchema.options.join(", ")})`,
	alias: "f",
	default: "text"
} };
function parsePATFormat(format) {
	const parsed = patFormatSchema.safeParse(format);
	if (!parsed.success) throw new Error(`Format "${format}" is invalid. Must be one of: ${patFormatSchema.options.join(", ")}`);
	return parsed.data;
}
function patScopeToString(scope) {
	switch (scope) {
		case PATScope.PAT_SCOPE_READ: return "read";
		case PATScope.PAT_SCOPE_WRITE: return "write";
		default: return "unknown";
	}
}
function transformPersonalAccessToken(pat) {
	return {
		name: pat.name,
		scopes: pat.scopes.map(patScopeToString)
	};
}
function getScopesFromWriteFlag(write) {
	return write ? [PATScope.PAT_SCOPE_READ, PATScope.PAT_SCOPE_WRITE] : [PATScope.PAT_SCOPE_READ];
}
function getScopeStringsFromWriteFlag(write) {
	return write ? ["read", "write"] : ["read"];
}
function printCreatedToken(name, token, write, format, action) {
	const scopes = getScopeStringsFromWriteFlag(write);
	if (format === "text") console.log(ml`
      Personal access token ${action} successfully.

        name: ${name}
      scopes: ${scopes.join("/")}
       token: ${token}

      Please save this token in a secure location. You won't be able to see it again.
    `);
	else console.log(JSON.stringify({
		name,
		scopes,
		token
	}));
}

//#endregion
//#region src/cli/user/pat/create.ts
const createCommand$1 = defineCommand({
	meta: {
		name: "create",
		description: "Create new personal access token"
	},
	args: {
		...commonArgs,
		...patFormatArgs,
		name: {
			type: "positional",
			description: "Token name",
			required: true
		},
		write: {
			type: "boolean",
			description: "Grant write permission (default: read-only)",
			default: false,
			alias: "w"
		}
	},
	run: withCommonArgs(async (args) => {
		const format = parsePATFormat(args.format);
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		const token = await fetchLatestToken(config, config.current_user);
		const client = await initOperatorClient(token);
		const scopes = getScopesFromWriteFlag(args.write);
		const result = await client.createPersonalAccessToken({
			name: args.name,
			scopes
		});
		if (!result.accessToken) throw new Error("Failed to create personal access token");
		printCreatedToken(args.name, result.accessToken, args.write, format, "created");
	})
});

//#endregion
//#region src/cli/user/pat/delete.ts
const deleteCommand$1 = defineCommand({
	meta: {
		name: "delete",
		description: "Delete personal access token"
	},
	args: {
		...commonArgs,
		name: {
			type: "positional",
			description: "Token name",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		const token = await fetchLatestToken(config, config.current_user);
		await (await initOperatorClient(token)).deletePersonalAccessToken({ name: args.name });
		consola$1.success(`Personal access token "${args.name}" deleted successfully.`);
	})
});

//#endregion
//#region src/cli/user/pat/list.ts
const listCommand$3 = defineCommand({
	meta: {
		name: "list",
		description: "List all personal access tokens"
	},
	args: {
		...commonArgs,
		...patFormatArgs
	},
	run: withCommonArgs(async (args) => {
		const format = parsePATFormat(args.format);
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		const token = await fetchLatestToken(config, config.current_user);
		const client = await initOperatorClient(token);
		const pats = await fetchAll(async (pageToken) => {
			const { personalAccessTokens, nextPageToken } = await client.listPersonalAccessTokens({ pageToken });
			return [personalAccessTokens, nextPageToken];
		});
		if (pats.length === 0) {
			consola$1.info(ml`
        No personal access tokens found.
        Please create a token using 'tailor-sdk user pat create' command.
      `);
			return;
		}
		if (format === "text") {
			const maxNameLength = Math.max(...pats.map((pat) => pat.name.length));
			pats.forEach((pat) => {
				const info = transformPersonalAccessToken(pat);
				const paddedName = info.name.padStart(maxNameLength);
				console.log(`${paddedName}: ${info.scopes.join("/")}`);
			});
		} else {
			const patInfos = pats.map(transformPersonalAccessToken);
			console.log(JSON.stringify(patInfos));
		}
	})
});

//#endregion
//#region src/cli/user/pat/update.ts
const updateCommand = defineCommand({
	meta: {
		name: "update",
		description: "Update personal access token (delete and recreate)"
	},
	args: {
		...commonArgs,
		...patFormatArgs,
		name: {
			type: "positional",
			description: "Token name",
			required: true
		},
		write: {
			type: "boolean",
			description: "Grant write permission (if not specified, keeps read-only)",
			default: false,
			alias: "w"
		}
	},
	run: withCommonArgs(async (args) => {
		const format = parsePATFormat(args.format);
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		const token = await fetchLatestToken(config, config.current_user);
		const client = await initOperatorClient(token);
		await client.deletePersonalAccessToken({ name: args.name });
		const scopes = getScopesFromWriteFlag(args.write);
		const result = await client.createPersonalAccessToken({
			name: args.name,
			scopes
		});
		if (!result.accessToken) throw new Error("Failed to create personal access token");
		printCreatedToken(args.name, result.accessToken, args.write, format, "updated");
	})
});

//#endregion
//#region src/cli/user/pat/index.ts
const patCommand = defineCommand({
	meta: {
		name: "pat",
		description: "Manage personal access tokens"
	},
	subCommands: {
		create: createCommand$1,
		delete: deleteCommand$1,
		list: listCommand$3,
		update: updateCommand
	},
	async run(context) {
		await runCommand(listCommand$3, { rawArgs: context.rawArgs || [] });
	}
});

//#endregion
//#region src/cli/user/use.ts
const useCommand = defineCommand({
	meta: {
		name: "use",
		description: "Set current user"
	},
	args: {
		...commonArgs,
		user: {
			type: "positional",
			description: "User email",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.users[args.user]) throw new Error(ml`
        User "${args.user}" not found.
        Please login first using 'tailor-sdk login' command to register this user.
      `);
		config.current_user = args.user;
		writePlatformConfig(config);
		consola$1.success(`Current user set to "${args.user}" successfully.`);
	})
});

//#endregion
//#region src/cli/user/index.ts
const userCommand = defineCommand({
	meta: {
		name: "user",
		description: "Manage Tailor Platform users"
	},
	subCommands: {
		current: currentCommand,
		list: listCommand$2,
		pat: patCommand,
		use: useCommand
	},
	async run() {
		await runCommand(listCommand$2, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/workflow/index.ts
const workflowCommand = defineCommand({
	meta: {
		name: "workflow",
		description: "Manage workflows"
	},
	subCommands: {
		list: listCommand$1,
		get: getCommand,
		start: startCommand,
		executions: executionsCommand,
		resume: resumeCommand
	},
	async run() {
		await runCommand(listCommand$1, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/workspace/index.ts
const workspaceCommand = defineCommand({
	meta: {
		name: "workspace",
		description: "Manage Tailor Platform workspaces"
	},
	subCommands: {
		create: createCommand,
		delete: deleteCommand,
		list: listCommand
	},
	async run() {
		await runCommand(listCommand, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/index.ts
register("tsx", import.meta.url, { data: {} });
const packageJson = await readPackageJson();
const mainCommand = defineCommand({
	meta: {
		name: packageJson.name,
		version: packageJson.version,
		description: packageJson.description || "Tailor CLI for managing Tailor Platform SDK applications"
	},
	subCommands: {
		apply: applyCommand,
		generate: generateCommand,
		init: initCommand,
		login: loginCommand,
		logout: logoutCommand,
		machineuser: machineuserCommand,
		oauth2client: oauth2clientCommand,
		profile: profileCommand,
		remove: removeCommand,
		show: showCommand,
		tailordb: tailordbCommand,
		secret: secretCommand,
		user: userCommand,
		workflow: workflowCommand,
		workspace: workspaceCommand
	}
});
runMain(mainCommand);

//#endregion
export {  };
//# sourceMappingURL=index.mjs.map