import logging
import os
from typing import AsyncIterable, Any, Coroutine

from dotenv import load_dotenv

from livekit.agents import (
    Agent,
    AgentSession,
    JobContext,
    JobProcess,
    RoomInputOptions,
    RoomOutputOptions,
    RunContext,
    WorkerOptions,
    cli,
    metrics,
    ChatContext,
    ChatMessage,
)
from livekit.agents.llm import function_tool, llm, ChatMessage
from livekit.agents.voice import MetricsCollectedEvent
from livekit.plugins import deepgram, openai, silero, speechmatics, elevenlabs
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from livekit.agents import Agent, get_job_context
from livekit import rtc

# uncomment to enable Krisp background voice/noise cancellation
# currently supported on Linux and MacOS
# from livekit.plugins import noise_cancellation

# Set Speechmatics API key
os.environ["SPEECHMATICS_API_KEY_ID"] = "3886f6f51b9341c08160618d4244e26a"

logger = logging.getLogger("basic-agent")

load_dotenv()


class CustomAgent(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="Your name is Kelly. You would interact with users via voice."
            "with that in mind keep your responses concise and to the point."
            "You are curious and friendly, and have a sense of humor.",
        )

    async def on_enter(self):
        # when the agent is added to the session, it'll generate a reply
        # according to its instructions
        self.session.generate_reply()

    # async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
    #     logger.info(f"xxxxxxxx User turn completed: {new_message}")

    def llm_node(
        self,
        chat_ctx: llm.ChatContext,
        tools: list[llm.FunctionTool],
        model_settings: dict,
    ) -> AsyncIterable[llm.ChatChunk | str] | Coroutine[Any, Any, AsyncIterable[llm.ChatChunk | str]]:
        # Access the last message which might be from lk.chat topic
        if chat_ctx.items and isinstance(chat_ctx.items[-1], ChatMessage):
            last_message = chat_ctx.items[-1]
            logger.info(f"Message content: {last_message.content}")
            
            # Check if this message has attributes from lk.chat
            if hasattr(last_message, 'metadata') and last_message.metadata:
                logger.info(f"Message metadata: {last_message.metadata}")
                # Access the attributes from the lk.chat topic
                if 'lk.chat' in last_message.metadata:
                    chat_attrs = last_message.metadata['lk.chat']
                    logger.info(f"lk.chat attributes: {chat_attrs}")
                    # Modify the message based on the attributes
                    if 'some_attribute' in chat_attrs:
                        # Modify the message based on the attribute
                        last_message.content = f"Modified: {last_message.content}"
                        logger.info(f"Modified content: {last_message.content}")
        
        # Call the parent implementation after manipulation
        return super().llm_node(chat_ctx, tools, model_settings)

    # all functions annotated with @function_tool will be passed to the LLM when this
    # agent is active
    @function_tool
    async def lookup_weather(
        self, context: RunContext, location: str, latitude: str, longitude: str
    ):
        """Called when the user asks for weather related information.
        Ensure the user's location (city or region) is provided.
        When given a location, please estimate the latitude and longitude of the location and
        do not ask the user for them.

        Args:
            location: The location they are asking for
            latitude: The latitude of the location
            longitude: The longitude of the location
        """

        logger.info(f"Looking up weather for {location}")

        return "sunny with a temperature of 70 degrees."


def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext):
    # each log entry will include these fields
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }
    await ctx.connect()
    logger.info(f"########entrypoint {ctx.job.metadata}")

    session = AgentSession(
        min_endpointing_delay=0.7,
        vad=ctx.proc.userdata["vad"],
        # any combination of STT, LLM, TTS, or realtime API can be used
        llm=openai.LLM(model="gpt-4o-mini"),
        stt=deepgram.STT(),

        # stt = speechmatics.STT(
        #     transcription_config=speechmatics.types.TranscriptionConfig(
        #         operating_point="enhanced", 
        #         enable_partials=False,
        #         language="en",
        #         output_locale="en-US",
        #         diarization="speaker",
        #         enable_entities=True,
        #         additional_vocab=[
        #             {
        #                 "content": "financial crisis"
        #             },
        #             {
        #                 "content": "gnocchi", 
        #                 "sounds_like": [
        #                 "nyohki", 
        #                 "nokey", 
        #                 "nochi"
        #                 ]
        #             },
        #             {
        #                 "content": "CEO",
        #                 "sounds_like": [
        #                 "C.E.O."
        #                 ]
        #             }
        #         ],
        #         max_delay=0.7,
        #         max_delay_mode="flexible"
        #     ), 
        #     audio_settings=speechmatics.types.AudioSettings(
        #         encoding="pcm_s16le",
        #         sample_rate=16000, 
        #     ),
        # ),
        #tts=openai.TTS(voice="ash"),
        tts=elevenlabs.TTS(),
        # use LiveKit's turn detection model
        turn_detection=MultilingualModel(),
    )

    # log metrics as they are emitted, and total usage after session is over
    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}")

    # shutdown callbacks are triggered when the session is over
    ctx.add_shutdown_callback(log_usage)

    # wait for a participant to join the room
    await ctx.wait_for_participant()

    await session.start(
        agent=CustomAgent(),
        room=ctx.room,
        # room_input_options=RoomInputOptions(),
        room_output_options=RoomOutputOptions(audio_enabled=True, sync_transcription=True),
    )

    session.output.set_audio_enabled(False)

    room = ctx.room
    @room.on("participant_connected")
    def on_participant_connected(participant: rtc.RemoteParticipant):
        logger.info("########participant connected: %s %s", participant.sid, participant.identity)



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