import os
import base64
import logging
from dotenv import load_dotenv

from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.util.types import AttributeValue
from livekit.agents.telemetry import set_tracer_provider

from livekit.agents import (NOT_GIVEN,Agent,AgentFalseInterruptionEvent,AgentSession,JobContext,JobProcess,MetricsCollectedEvent,RoomInputOptions,RoomOutputOptions,RunContext,WorkerOptions,get_job_context,cli,metrics)
from livekit import rtc, api
from livekit.agents.llm import function_tool
from livekit.plugins import (google, noise_cancellation, silero)
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from livekit.plugins.turn_detector.english import EnglishModel

logger = logging.getLogger("agent")
logger.setLevel(logging.INFO)
load_dotenv()

# Functions -------------------------------------------------------------------------------------------------------------------------------------------

async def hangup_call():
    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,
        )
    )

# ---------------------------------------------------------------------------------------------------------------------------------------------------------------


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions=
"""
                🎯 Identity & Role
                Your name is Rachel. You are a female AI voice representative of Agent Flow Solutions, 
                a company that provides customized AI Voice Agent solutions for businesses. 
                You communicate in a natural, friendly, and professional tone, similar to a real human female voice agent.
                You are fluent in English and speak in a natural, conversational way.

                🗣️ Core Objective
                Your primary goal is to conduct a short discovery conversation to understand the user’s business requirements 
                and help schedule a product demo or provide relevant information.

                🧩 Conversation Flow & Required Questions
                Start every conversation with a warm greeting:

                1. Greeting
                    “Hello, This is Rachel from Agent Flow Solutions. How are you ?”

                2. Conversation Script (Dynamic Question Flow)
                    Ask questions naturally, adapting based on user responses. 
                    You may paraphrase slightly depending on the flow, 
                    but you must cover these core areas. 
                    Also, you must follow the proper flow and not rush to the next question before receiving a response.

                    Step 1: Greeting & Introduction
                    “So We help businesses automate their customer interactions using AI Voice Agents.”
                    “Can you please tell me a little about your business or what industry you’re in?”
                    → If user answers:
                        Acknowledge naturally:
                    “That’s great! [Industry name] is definitely one of the areas where AI automation can make a big difference.”
                    
                    Step 2: Interest Area
                    “Are you mainly looking to improve customer support, sales follow-ups, or outbound campaigns like reminders and promotions?”
                    → If user mentions any area or something similar:
                    “Perfect, that’s exactly where our solutions can help the most.”
                    → If user is unsure or something similar:
                    “No worries, I can give you a quick overview of how we help in each area so you can decide what fits best.”
                    
                    Step 3: Challenges
                    “What’s the biggest challenge you’re currently facing — is it time consumption, staffing limitations, or maintaining response consistency?”
                    → If user shares challenge or something similar:
                    “I completely understand. That’s a common issue for many of our clients before they switch to automation.”
                    → If user says ‘no major challenge’ or something similar:
                    “That’s good to hear! In that case, our solution can still help optimize your team’s time and scale customer interactions smoothly.”
                    
                    Step 4: Asking About Future Plans
                    “When are you planning to implement a new solution?”
                    → If user shows interest or urgency:
                    “That’s great! This is the perfect time to explore a quick demo and see what best fits your setup.”
                    → If user prefers to wait or postpone:
                    “Got it! I can still show you a short demo now so you’ll have a clear idea when you’re ready to move forward.”
                    
                    Step 5: Demo Invitation
                    “Would you like to see a quick demo this week to understand how it works?”
                    → If user says Yes or something similar:
                    “Awesome! What day and time would be convenient for a short 15-minute demo?”
                    → If user says No or Not right now or something similar:
                    “No problem at all. Would you prefer that I share a short demo video or some details over email or WhatsApp instead?”
                    
                    Step 6: Contact & Demo Scheduling
                    “Can I have your preferred email address or WhatsApp number to send the demo link or information?”
                    → If user shares details or something similar:
                    “Thank you! I’ll send the demo details right away and confirm the slot.”
                    → If user declines or something similar:
                    “That’s completely fine. You can always visit our website or reach out whenever you’d like a walkthrough.”
                    
                    Step 7: Closing
                    “Thank you for your time today! It was great speaking with you. I’ll make sure you get the demo details shortly.”
                    “Have a wonderful day ahead!”

                    step 8: End Call Function
                    "After the closing phrase: 'Have a wonderful day ahead!', your next and final step must be to call the "end_call" function to terminate the conversation."

                ⚙️ Tone, Personality & Behavioral Rules
                    ● Tone: Friendly, respectful, confident, and approachable.
                    ● Emotion: Lightly expressive and empathetic.
                    ● Politeness: Always use respectful forms (“Sir/Ma’am”).
                    ● Pacing: Natural spoken rhythm (not too fast or too robotic).
                    ● Response Length: 1–3 sentences per turn.
                    ● Awareness: Keep track of context — remember user preferences and answers.
                    ● Adaptability: Modify follow-ups based on user mood (curious, busy, skeptical, etc.).
                    ● Endings: Always close conversations positively with gratitude and clarity on next steps.

                🤝 Closing Example
                    ● “Thank you so much for your time! I’ll send the demo link to your email shortly.”

                🧠 Summary Instruction
                You are Rachel, a professional AI voice representative from Agent Flow Solutions. 
                You greet every user politely, ask discovery questions naturally in English, 
                understand their business needs, and help schedule a product demo or share relevant information. 
                You must maintain a human-like, kind, and professional tone throughout the conversation.
                """, 
        )

    async def on_enter(self):
        self.session.generate_reply(instructions="Greet the user properly by saying hello how are you ?")  

    # to hang up the call as part of a function call
    @function_tool
    async def end_call(self, ctx: RunContext):
        """Called when the user wants to end the call"""
        await ctx.wait_for_playout() # let the agent finish speaking
        await hangup_call()


def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load(
        min_speech_duration=0.05,
        min_silence_duration=0.4,
        prefix_padding_duration=0.5,
        max_buffered_speech=60,
        activation_threshold=0.5,
        sample_rate=8000,    # DEFAULT IS 16000
        force_cpu=True
)


async def entrypoint(ctx: JobContext):
    # Add any other context you want in all log entries here
    ctx.log_context_fields = {"room": ctx.room.name}

    # Set up a voice AI pipeline using OpenAI, Cartesia, Deepgram, and the LiveKit turn detector
    session = AgentSession(
        vad=ctx.proc.userdata["vad"],
        llm=google.LLM(model="gemini-2.5-flash-lite-preview-09-2025"),   # gemini-2.0-flash-exp # gemini-2.5-flash-lite
        stt=google.STT(model="telephony", spoken_punctuation=False, languages="en-IN", detect_language=True, interim_results=True, punctuate=True, use_streaming=True ), 
        tts=google.TTS(gender="female", voice_name="en-IN-Chirp3-HD-Achernar",language="en-IN", use_streaming=True),
        # tts = google.beta.GeminiTTS(model="gemini-2.5-flash-preview-tts", voice_name="Zephyr", instructions="Speak in a friendly and engaging tone."),
        turn_detection=MultilingualModel(),  # MultilingualModel # EnglishModel
        preemptive_generation=True, # Whether to speculatively begin LLM and TTS requests before an end-of-turn is detected. When True, the agent sends inference calls as soon as a user transcript is received rather than waiting for a definitive turn boundary. This can reduce response latency by overlapping model inference with user audio, but may incur extra compute if the user interrupts or revises mid-utterance.
        min_endpointing_delay=0.3,   # DEFAULT 0.4
        max_endpointing_delay=3   # DEFAULT 6
    )


    # sometimes background noise could interrupt the agent session, these are considered false positive interruptions
    # when it's detected, you may resume the agent's speech
    # @session.on("agent_false_interruption")
    # def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
    #     logger.info("false positive interruption, resuming")
    #     session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)

    # Metrics collection, to measure pipeline performance
    # For more information, see https://docs.livekit.io/agents/build/metrics/
    usage_collector = metrics.UsageCollector()

    @session.on("metrics_collected")
    def _on_metrics_collected(ev: MetricsCollectedEvent):
        metrics.log_metrics(ev.metrics)
        usage_collector.collect(ev.metrics)

    async def log_usage():
        summary = usage_collector.get_summary()
        logger.info(f"Usage: {summary}")

    ctx.add_shutdown_callback(log_usage)

    # # Add a virtual avatar to the session, if desired
    # # For other providers, see https://docs.livekit.io/agents/integrations/avatar/
    # avatar = hedra.AvatarSession(
    #   avatar_id="...",  # See https://docs.livekit.io/agents/integrations/avatar/hedra
    # )
    # # Start the avatar and wait for it to join
    # await avatar.start(session, room=ctx.room)

    # Start the session, which initializes the voice pipeline and warms up the models
    await session.start(
        agent=Assistant(),
        room=ctx.room,
        room_input_options=RoomInputOptions(noise_cancellation=noise_cancellation.BVC()),
        room_output_options=RoomOutputOptions(transcription_enabled=True, sync_transcription=True)   # -> Check other Parameters
    )

    # Join the room and connect to the user
    await ctx.connect()


if __name__ == "__main__":
    cli.run_app(WorkerOptions(agent_name="simple-agent-1",entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
