import * as plugins from './aibridge.plugins.js';
import * as paths from './aibridge.paths.js';
import { AiBridgeDb } from './aibridge.classes.aibridgedb.js';
import { OpenAiBridge } from './aibridge.classes.openaibridge.js';

export class AiBridge {
  public projectinfo: plugins.projectinfo.ProjectInfo;
  public serverInstance: plugins.loleServiceserver.ServiceServer;
  public serviceQenv = new plugins.qenv.Qenv('./', './.nogit');
  public aibridgeDb: AiBridgeDb;

  public openAiBridge: OpenAiBridge;

  public typedrouter = new plugins.typedrequest.TypedRouter();

  public async start() {
    this.aibridgeDb = new AiBridgeDb(this);
    await this.aibridgeDb.start();
    this.projectinfo = new plugins.projectinfo.ProjectInfo(paths.packageDir);
    this.openAiBridge = new OpenAiBridge(this);
    await this.openAiBridge.start();

    // server
    this.serverInstance = new plugins.loleServiceserver.ServiceServer({
      serviceDomain: 'aibridge.lossless.one',
      serviceName: 'aibridge',
      serviceVersion: this.projectinfo.npm.version,
      addCustomRoutes: async (serverArg) => {
        // any custom route configs go here
      },
    });

    // lets implemenet the actual typedrequest functions
    this.typedrouter.addTypedHandler<plugins.lointAiBridge.requests.IReq_Chat>(new plugins.typedrequest.TypedHandler('chat', async reqArg => {
      const resultChat = await this.openAiBridge.chat(reqArg.chat.systemMessage, reqArg.chat.messages[reqArg.chat.messages.length - 1].content, reqArg.chat.messages);
      return {
        chat: reqArg.chat,
        latestMessage: resultChat.message.content,
      }
    }))

    await this.serverInstance.start();
    this.serverInstance.typedServer.typedrouter.addTypedRouter(this.typedrouter);
  }

  public async stop() {
    await this.serverInstance.stop();
    await this.aibridgeDb.stop();
  }
}