import 'dotenv/config';

import { voice } from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
import { createServerSupabase } from '@/lib/superbase/server';
import redisClient from '@/lib/redisClient';


/**
 * Simple Interview Agent runner that:
 * - uses Gemini Live (via @livekit/agents-plugin-google)
 * - saves ephemeral context to Redis
 * - persists responses and session metadata to Supabase
 *
 * Note: adapt event names and methods to the exact @livekit/agents version if necessary.
 */

export async function startAgentProcess() {
  const session = new voice.AgentSession({
    llm: new google.beta.realtime.RealtimeModel({
      model: 'gemini-2.5-flash-native-audio-preview-12-2025',
      voice: 'Puck',
      temperature: 0.7,
      instructions: `You are an AI interviewer. Ask one question at a time, wait for the candidate's complete answer, ask brief follow-ups if needed, be professional and encouraging.`,
      apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY,
    }),
    stt: 'google/speech-to-text',
    tts: 'google/text-to-speech',
  });

  // When agent commits speech (agent spoke)
  session.on('agent_speech_committed', async (ev: any) => {
    try {
      const room = ev.room ?? ev.roomName ?? ev.roomId;
      const text = ev.transcript ?? ev.text ?? null;
      if (!room || !text) return;
      const key = `interview:${room}:responses`;
      await redisClient.set(key, JSON.stringify({ type: 'agent', text, ts: Date.now() }), { ex: 3600 });

    } catch (e) { console.error('agent_speech_committed handler error', e); }
  });

  // When candidate/user speech is committed (user finished speaking)
  session.on('user_speech_committed', async (ev: any) => {
    try {
      const room = ev.room ?? ev.roomName ?? ev.roomId;
      const text = ev.transcript ?? ev.text ?? null;
      if (!room || !text) return;

      // push to Redis
      const key = `interview:${room}:responses`;
      await redisClient.set(key, JSON.stringify({ type: 'candidate', text, ts: Date.now() }), { ex: 3600 });

      // optional: basic follow-up logic (word count)
      const wordCount = text.trim().split(/\s+/).length;
      if (wordCount < 8) {
        await session.say('Thanks — could you elaborate a bit more on that?');
      } else {
        // move to next question (simple placeholder)
        await session.say('Great. Next question: Tell me about a challenging project you worked on.');
      }
    } catch (e) { console.error('user_speech_committed handler error', e); }
  });

  // session end or cleanup hook (event name may vary)
  session.on('session_end', async (ev: any) => {
    try {
      const room = ev.room ?? ev.roomName ?? ev.roomId;
      console.log("🚀 ~ session_end ~ room:", room)
      if (!room) return;
      const key = `interview:${room}:responses`;
      const items = await redisClient.get(key) || [];
      const transcript = items.map((i: any) => JSON.parse(i)).reverse().map((r: any) => `${r.type}: ${r.text}`).join('\n');
      await redisClient.del(key);
    } catch (e) { console.error('session_end handler error', e); }
  });

  // Start listening for rooms/requests. The actual startup depends on @livekit/agents runner usage.
  // If your version supports session.listen() or a runner, call it. Otherwise the package's CLI might be used.
  if (typeof (session as any).listen === 'function') {
    await (session as any).listen();
    console.log('AgentSession listening');
  } else {
    console.log('AgentSession ready (no listen method detected). Ensure your @livekit/agents usage starts sessions appropriately.');
  }
}