import { createRequire } from 'module';
import '../../lib/getRandomValues.polyfill.js';
import { LocalStorage } from 'node-localstorage';
import { ClockDefinition, HTTPDefinition, KVStoreDefinition, LoggerDefinition, ModlogDefinition, SchedulerDefinition, SettingsDefinition, StreamBrokerDefinition, V2EventsDefinition, } from '@devvit/protos';
import { StringUtil } from '@devvit/shared-types/StringUtil.js';
import path from 'node:path';
import { CommonRuntime } from '../../common/runtime/CommonRuntime.js';
import { Never } from '../../common/runtime/GCPolicy.js';
import { NODE_HOSTNAME } from '@devvit/shared-types/HostnameUtil.js';
import { Log } from '../../lib/loggers/Log.js';
import Clock from '../../plugins/Clock.js';
import { LocalStorageBroker } from '../../plugins/LocalStorageBroker.js';
import { LocalStorageKV } from '../../plugins/LocalStorageKV.js';
import Modlog from '../../plugins/Modlog.js';
import { Scheduler } from '../../plugins/Scheduler.js';
import Settings from '../../plugins/Settings.js';
import { V2Events } from '../../plugins/V2Events.js';
import { NodeHTTP } from '../../plugins/http/NodeHttp.js';
import { ConsoleLogger } from '../../plugins/logger/ConsoleLogger.js';
const require = createRequire(import.meta.url);
export class NodeRuntime extends CommonRuntime {
    constructor(namespace = NODE_HOSTNAME, gcPolicy = Never, workerErrorLogger = (err) => Log.error(StringUtil.caughtToString(err))) {
        super(namespace, gcPolicy, workerErrorLogger);
    }
    pathForName(workerNameOrModuleFile) {
        try {
            return require.resolve(`@devvit/runtimes/worker.${workerNameOrModuleFile}.cjs`);
        }
        catch {
            return require.resolve(workerNameOrModuleFile);
        }
    }
    async loadPlugins(dispatcher) {
        const kvStorage = new LocalStorage(path.join(process.cwd(), './.devvitLocalStorage/kv'));
        const brokerStorage = new LocalStorage(path.join(process.cwd(), './.devvitLocalStorage/broker'));
        this.provide(LoggerDefinition, new ConsoleLogger());
        this.provide(KVStoreDefinition, new LocalStorageKV(kvStorage));
        this.provide(StreamBrokerDefinition, new LocalStorageBroker(brokerStorage));
        this.provide(ClockDefinition, new Clock());
        this.provide(HTTPDefinition, new NodeHTTP(dispatcher));
        this.provide(ModlogDefinition, new Modlog());
        this.provide(V2EventsDefinition, new V2Events());
        this.provide(SchedulerDefinition, new Scheduler(dispatcher));
        this.provide(SettingsDefinition, new Settings());
    }
    async dispose() {
        await super.dispose();
    }
}
// to-do: you probably shouldn't have to subclass the runtime to provide
// different configurations.
export class NodeRuntimeNoPlugins extends NodeRuntime {
    async loadPlugins() { }
}
