import { NextResponse } from "next/server";
import {
  AccessToken,
  type AccessTokenOptions,
  type VideoGrant,
} from "livekit-server-sdk";
import { RoomAgentDispatch, RoomConfiguration } from "@livekit/protocol";
import { meetingGetOne } from "@/app/modules/meetings/types";

// NOTE: you are expected to define the following environment variables in `.env.local`:
const API_KEY = process.env.LIVEKIT_API_KEY;
const API_SECRET = process.env.LIVEKIT_API_SECRET;
const LIVEKIT_URL = process.env.LIVEKIT_URL;

// don't cache the results
export const revalidate = 0;

export type ConnectionDetails = {
  serverUrl: string;
  roomName: string;
  participantName: string;
  participantToken: string;
};

export async function POST(req: Request) {
  try {
    if (LIVEKIT_URL === undefined) {
      throw new Error("LIVEKIT_URL is not defined");
    }
    if (API_KEY === undefined) {
      throw new Error("LIVEKIT_API_KEY is not defined");
    }
    if (API_SECRET === undefined) {
      throw new Error("LIVEKIT_API_SECRET is not defined");
    }

    // Parse agent configuration from request body
    const body = await req.json();
    const meetingData: meetingGetOne | undefined = body?.meetingData;
    const agentNameFromBody: string | undefined = body?.agentName;
    const agentInstructionFromBody: string | undefined = body?.agentInstruction;
    const contextFromBody: Record<string, unknown> | undefined = body?.context;

    // Generate participant token
    const participantName = "user";
    const participantIdentity =
      meetingData?.userId ?? `user-${Math.random().toString(36).slice(2, 8)}`;
    const roomName =
      meetingData?.id ?? `room-${Math.random().toString(36).slice(2, 8)}`;

    // Resolve agent name and metadata to send to the agent
    const agentName = agentNameFromBody ?? meetingData?.agent?.name;
    const instructions =
      agentInstructionFromBody ??
      meetingData?.agent?.instruction ??
      "You are a helpful career assistant. Keep replies concise.";
    const metadata = JSON.stringify({
      instructions,
      context: contextFromBody ?? {
        careerField: "Software Engineering",
        idealJob: "Senior Developer",
      },
    });

    const participantToken = await createParticipantToken(
      { identity: participantIdentity, name: participantName },
      roomName,
      agentName,
      metadata
    );

    // Return connection details
    const data: ConnectionDetails = {
      serverUrl: LIVEKIT_URL,
      roomName,
      participantToken: participantToken,
      participantName,
    };
    const headers = new Headers({
      "Cache-Control": "no-store",
    });
    return NextResponse.json(data, { headers });
  } catch (error) {
    if (error instanceof Error) {
      console.error(error);
      return new NextResponse(error.message, { status: 500 });
    }
  }
}

function createParticipantToken(
  userInfo: AccessTokenOptions,
  roomName: string,
  agentName?: string,
  agentMetadata?: string
): Promise<string> {
  const at = new AccessToken(API_KEY, API_SECRET, {
    ...userInfo,
    ttl: "15m",
  });

  const grant: VideoGrant = {
    room: roomName,
    roomJoin: true,
    canPublish: true,
    canPublishData: true,
    canSubscribe: true,
  };
  at.addGrant(grant);

  // Attach agent dispatch and metadata if an agent name is provided
  if (agentName && agentName.trim().length > 0) {
    at.roomConfig = new RoomConfiguration({
      metadata: agentMetadata,
      agents: [
        new RoomAgentDispatch({
          agentName,
          metadata: agentMetadata,
        }),
      ],
    });
    console.log(`Dispatching agent with name: ${agentName}`);
  } else {
    console.log("No valid agentName provided. Skipping agent dispatch.");
  }

  return at.toJwt();
}
