
// src/agent.ts
import dotenv from 'dotenv';
dotenv.config();

import * as livekit from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';

const { LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY } = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL || !GOOGLE_API_KEY) {
  throw new Error('Missing env vars: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY');
}

const workerOptions: livekit.WorkerOptions = {
  apiKey: LIVEKIT_API_KEY,
  apiSecret: LIVEKIT_API_SECRET,
  callbackUrl: LIVEKIT_URL,
  participantLimit: 0,
  async workerInit() {
    console.log('Worker initialized');
  },
  async jobRequest(ctx: livekit.JobContext) {
    console.log('Job request for room:', ctx.room.name);

    // Connect agent to room (audio only)
    await ctx.connect({ autoSubscribe: livekit.AutoSubscribe.AUDIO_ONLY });

    // Create Gemini RealtimeModel via plugin
    const llm = new google.realtime.RealtimeModel({
      apiKey: GOOGLE_API_KEY,
      model: 'gemini-2.0-flash-exp',
      voice: 'Puck',
      temperature: 0.7,
      instructions: 'You are a friendly interviewer. Ask one question at a time.',
    });

    // livekit.AgentSession class may be available off the package. Use the helper from the package:
    const session = new livekit.AgentSession?.({ room: ctx.room, llm } as any) ?? null;

    if (!session) {
      // fallback: construct session via the livekit API surface used by this package version
      // many versions expose a helper to create a session; use startWithModel if available
      if (typeof livekit.createAgentSession === 'function') {
        // createAgentSession is a hypothetical helper — prefer to call the package's provided API
        console.log('Using createAgentSession helper');
        // @ts-ignore
        const created = await livekit.createAgentSession({ room: ctx.room, llm });
        // assume created has start/say/on methods
        await created.start();
        try { await created.say('Hello — I will be your interviewer.'); } catch (e) {}
        return;
      }
      throw new Error('AgentSession API not found on @livekit/agents; confirm package version');
    }

    // start session and handle transcripts/responses
    await session.start();
    session.on('transcript', (evt: any) => {
      console.log('transcript', evt);
    });
    session.on('response', (r: any) => {
      console.log('response', r?.text);
    });

    try {
      await session.say('Hello — I will be your interviewer. Tell me about your most recent project.');
    } catch (e) {
      console.warn('greeting failed', e);
    }
  },
};

export default workerOptions;