import { z } from 'zod';
import { getCommand } from "../../../command-prefix.js";
import { getIONHost } from "../../../config.js";
import { spawnInherit } from "../../../node-compat/proc.js";
import * as tui from "../../../tui.js";
import { createSubcommand } from "../../../types.js";
import { getIdentifierRegion } from "../region-lookup.js";
const args = z.object({
    source: z.string().describe('the source file'),
    destination: z.string().optional().describe('the destination file'),
});
const options = z.object({
    identifier: z.string().optional().describe('The project or deployment id to use'),
});
export const downloadCommand = createSubcommand({
    name: 'download',
    aliases: ['get'],
    description: 'Download a file using security copy',
    tags: ['read-only', 'slow', 'requires-auth', 'requires-deployment'],
    idempotent: true,
    examples: [
        {
            command: getCommand('cloud scp download /var/log/app.log'),
            description: 'Download to current directory',
        },
        {
            command: getCommand('cloud scp download /var/log/app.log ./logs/'),
            description: 'Download to specific path',
        },
        {
            command: getCommand('cloud scp download /app/config.json --identifier=proj_abc123xyz'),
            description: 'Download from specific project',
        },
        {
            command: getCommand('cloud scp download ~/logs/*.log ./logs/'),
            description: 'Download multiple files',
        },
    ],
    requires: { apiClient: true, auth: true },
    optional: { project: true },
    prerequisites: ['cloud deploy'],
    schema: {
        args,
        options,
        response: z.object({
            success: z.boolean().describe('Whether download succeeded'),
            source: z.string().describe('Remote source path'),
            destination: z.string().describe('Local destination path'),
            identifier: z.string().describe('Project or deployment identifier'),
        }),
    },
    async handler(ctx) {
        const { apiClient, args, opts, project, projectDir, config, logger, auth } = ctx;
        let identifier = opts?.identifier ?? project?.projectId;
        if (!identifier) {
            identifier = await tui.showProjectList(apiClient, true);
        }
        // Look up region from identifier (project/deployment/sandbox)
        const profileName = config?.name;
        // For sandbox identifiers, use saved org preference (no prompting)
        const orgId = identifier.startsWith('sbx_') ? config?.preferences?.orgId : undefined;
        const region = await getIdentifierRegion(logger, auth, apiClient, profileName, identifier, orgId, config);
        const hostname = getIONHost(config, region);
        const destination = args.destination ?? projectDir;
        try {
            const { exitCode } = await spawnInherit({
                cmd: ['scp', `${identifier}@${hostname}:${args.source}`, destination],
                cwd: projectDir,
            });
            if (exitCode !== 0) {
                tui.error(`SCP download failed: ${identifier}@${hostname}:${args.source} -> ${destination} (exit code: ${exitCode})`);
                process.exit(exitCode ?? 1);
            }
            return {
                success: true,
                source: args.source,
                destination,
                identifier,
            };
        }
        catch (error) {
            tui.error(`SCP download error: ${error instanceof Error ? error.message : 'Unknown error'}`);
            process.exit(1);
        }
    },
});
//# sourceMappingURL=download.js.map