import { projectGet, sandboxGet, deploymentGet } from '@agentuity/server';
import { getResourceRegion, setResourceRegion } from '../../cache';
import { getGlobalCatalystAPIClient } from '../../config';
import * as tui from '../../tui';
import { ErrorCode } from '../../errors';
/**
 * Determine the type of identifier based on its prefix
 */
export function getIdentifierType(identifier) {
    if (identifier.startsWith('proj_')) {
        return 'project';
    }
    if (identifier.startsWith('deploy_')) {
        return 'deployment';
    }
    if (identifier.startsWith('sbx_')) {
        return 'sandbox';
    }
    // Default to project for unknown prefixes
    return 'project';
}
/**
 * Look up the region for a project, deployment, or sandbox identifier.
 * Uses cache-first strategy with API fallback.
 */
export async function getIdentifierRegion(logger, auth, apiClient, profileName = 'production', identifier, orgId) {
    const identifierType = getIdentifierType(identifier);
    // For project, deployment, and sandbox, check cache first
    const cachedRegion = await getResourceRegion(identifierType, profileName, identifier);
    if (cachedRegion) {
        logger.trace(`[region-lookup] Found cached region for ${identifier}: ${cachedRegion}`);
        return cachedRegion;
    }
    logger.trace(`[region-lookup] Cache miss for ${identifier}, fetching from API`);
    let region = null;
    if (identifierType === 'project') {
        const project = await projectGet(apiClient, { id: identifier, mask: true, keys: false });
        region = project.cloudRegion ?? null;
    }
    else if (identifierType === 'deployment') {
        const deployment = await deploymentGet(apiClient, identifier);
        region = deployment.cloudRegion ?? null;
    }
    else {
        // sandbox
        const globalClient = await getGlobalCatalystAPIClient(logger, auth, profileName);
        const sandbox = await sandboxGet(globalClient, { sandboxId: identifier, orgId });
        region = sandbox.region ?? null;
    }
    if (!region) {
        tui.fatal(`Could not determine region for ${identifierType} '${identifier}'. Use --region flag to specify.`, ErrorCode.RESOURCE_NOT_FOUND);
    }
    // Cache the result
    await setResourceRegion(identifierType, profileName, identifier, region);
    logger.trace(`[region-lookup] Cached region for ${identifier}: ${region}`);
    return region;
}
/**
 * Cache the region for a project after creation
 */
export async function cacheProjectRegion(profileName = 'production', projectId, region) {
    await setResourceRegion('project', profileName, projectId, region);
}
//# sourceMappingURL=region-lookup.js.map