import '../assert_dev_env.js';
import { bootstrap_backend } from './bootstrap_backend.js';
import { serialize_bootstrapped_handle } from './setup.js';
/**
 * Default project-name → backend-name reduction: strips the
 * `cross_backend_` prefix plus an optional `ts_` discriminator (the TS
 * canonical backends carry it to distinguish JS runtimes). So
 * `cross_backend_ts_deno` → `deno` and `cross_backend_rust` → `rust`.
 */
const DEFAULT_PROJECT_NAME_PREFIX = /^cross_backend_(?:ts_)?/;
/**
 * Build a vitest `globalSetup` default export. Returns the
 * `(project) => teardown` function vitest 4 expects.
 */
export const create_cross_backend_global_setup = ({ configs, derive_name = (project_name) => project_name.replace(DEFAULT_PROJECT_NAME_PREFIX, ''), provide_key = 'backend_handle', }) => {
    return async (project) => {
        const name = derive_name(project.name);
        const factory = configs[name];
        if (!factory) {
            throw new Error(`Could not derive backend config from vitest project '${project.name}' ` +
                `(derived name '${name}') — expected one of: ${Object.keys(configs).join(', ')}`);
        }
        const bootstrapped = await bootstrap_backend(factory());
        // vitest's `provide` is keyed on the consumer-augmented `ProvidedContext`;
        // the generic key is a plain string, so cast past the keyof constraint.
        project.provide(provide_key, serialize_bootstrapped_handle(bootstrapped));
        return async () => {
            await bootstrapped.teardown();
        };
    };
};
