from __future__ import annotations

import asyncio
import logging
from dotenv import load_dotenv
import json
import os
from typing import Any
from livekit.plugins.openai import realtime
from openai.types.beta.realtime.session import TurnDetection

from livekit import rtc, api
from livekit.agents import (
    AgentSession,
    Agent,
    JobContext,
    function_tool,
    RunContext,
    get_job_context,
    cli,
    WorkerOptions,
    RoomInputOptions,
)
from livekit.plugins import (
    google,
    noise_cancellation,  # noqa: F401
)
from prompt import prompts

load_dotenv()

logger = logging.getLogger("outbound-caller")
logger.setLevel(logging.INFO)

outbound_trunk_id = "ST_DYey6rphZDwX"


class OutboundCaller(Agent):
    def __init__(
        self,
    ):
        super().__init__(instructions="You are Parth a customer support voice agent investigating Failed Deliveries")
        # keep reference to the participant for transfers
        self.participant: rtc.RemoteParticipant | None = None

    def set_participant(self, participant: rtc.RemoteParticipant):
        self.participant = participant
    
    @function_tool()
    async def hangup_call(self):
        ctx = get_job_context()
        if ctx is None:
            # Not running in a job context
            return
        
        await ctx.api.room.delete_room(
            api.DeleteRoomRequest(
                room=ctx.room.name,
            )
        )

async def entrypoint(ctx: JobContext):
    logger.info(f"connecting to room {ctx.room.name}")
    print(1)
        # when dispatching the agent, we'll pass it the approriate info to dial the user
    # dial_info is a dict with the following keys:
    # - phone_number: the phone number to dial
    # - transfer_to: the phone number to transfer the call to when requested
    dial_info = json.loads(ctx.job.metadata)
    participant_identity = phone_number = dial_info["phone_number"]

    await ctx.connect()
    instruction = """You are Parth a customer support agent who assists with failed deliveries. You are access to a function hangup_call use it to hangup the call once the conversation is over."""
    # look up the user's phone number and appointment details
    agent = OutboundCaller()

    session_google_india = AgentSession(
    llm=google.beta.realtime.RealtimeModel(
        voice="Orus",
        temperature=0.3,
        instructions=instruction,
        language="en-IN"
        ),
    )

    session = session_google_india
    # start the session first before dialing, to ensure that when the user picks up
    # the agent does not miss anything the user says
    session_started = asyncio.create_task(
        session.start(
            agent=agent,
            room=ctx.room,
            room_input_options=RoomInputOptions(
                # enable Krisp background voice and noise removal
                # noise_cancellation=noise_cancellation.BVCTelephony(),
            ),
        )
    )

    # `create_sip_participant` starts dialing the user
    try:
        await ctx.api.sip.create_sip_participant(
            api.CreateSIPParticipantRequest(
                room_name=ctx.room.name,
                sip_trunk_id=outbound_trunk_id,
                sip_call_to=phone_number,
                participant_identity=participant_identity,
                # function blocks until user answers the call, or if the call fails
                wait_until_answered=True,
            )
        )

        # wait for the agent session start and participant join
        await session_started
        participant = await ctx.wait_for_participant(identity=participant_identity)
        logger.info(f"participant joined: {participant.identity}")

        agent.set_participant(participant)

        await session.generate_reply(
        instructions=instruction + """Say the world "Hello" nothing else"""
        )

    except api.TwirpError as e:
        logger.error(
            f"error creating SIP participant: {e.message}, "
            f"SIP status: {e.metadata.get('sip_status_code')} "
            f"{e.metadata.get('sip_status')}"
        )
        ctx.shutdown()
    print(session.history.to_dict())


if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            agent_name="outbound-caller",
        )
    )