import path from "node:path";
import { parseSdkRegistryFromContent, parseSdkRegistryEntries, } from "../../../../parsing/sdk-registry.js";
import { getLogger } from "../../../../util/logger.js";
export const SDK_REGISTRY_PATH = "server/apis/index.ts";
const SDK_REGISTRY_DIR = "server/apis";
const RESOLUTION_EXTENSIONS = [".ts", ".tsx", ".js"];
export async function parseSdkRegistryEntryPoints(registryContent, pathExists) {
    return parseSdkRegistryFromContent(registryContent, (importPath) => resolveImportPath(importPath, pathExists));
}
export async function readSdkRegistryEntryPoints(fs) {
    try {
        if (!(await fs.pathExists(SDK_REGISTRY_PATH))) {
            return new Map();
        }
        const registryContent = await fs.readFile(SDK_REGISTRY_PATH);
        return parseSdkRegistryEntryPoints(registryContent, fs.pathExists);
    }
    catch (error) {
        getLogger().warn(`[sdk-registry] Failed to read or parse SDK registry at ${SDK_REGISTRY_PATH}`, error instanceof Error ? error.message : String(error));
        return new Map();
    }
}
export async function readSdkRegistryEntries(fs) {
    try {
        if (!(await fs.pathExists(SDK_REGISTRY_PATH))) {
            return new Map();
        }
        const registryContent = await fs.readFile(SDK_REGISTRY_PATH);
        return parseSdkRegistryEntries(registryContent, (importPath) => resolveImportPath(importPath, fs.pathExists));
    }
    catch (error) {
        getLogger().warn(`[sdk-registry] Failed to read or parse SDK registry at ${SDK_REGISTRY_PATH}`, error instanceof Error ? error.message : String(error));
        return new Map();
    }
}
export async function resolveSdkApiEntryPoint(apiName, fs, cachedEntryPoints) {
    const cached = cachedEntryPoints?.get(apiName);
    if (cached !== undefined) {
        return cached;
    }
    const entryPoints = await readSdkRegistryEntryPoints(fs);
    return entryPoints.get(apiName);
}
export async function resolveSdkApiEntry(apiName, fs) {
    const entries = await readSdkRegistryEntries(fs);
    return entries.get(apiName);
}
async function resolveImportPath(importPath, pathExists) {
    if (!importPath.startsWith(".")) {
        return undefined;
    }
    const normalizedBase = path.posix
        .normalize(path.posix.join(SDK_REGISTRY_DIR, importPath))
        .replace(/\.(js|ts|tsx)$/, "");
    for (const extension of RESOLUTION_EXTENSIONS) {
        const candidate = `${normalizedBase}${extension}`;
        if (await pathExists(candidate)) {
            return candidate;
        }
    }
    return undefined;
}
//# sourceMappingURL=sdk-registry.js.map