from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
import time
import asyncio

from livekit.agents import (
    Agent,
    AgentSession,
    JobContext,
    WorkerOptions,
    cli,
)
from livekit.plugins import deepgram, elevenlabs, openai, silero, langchain
import logging

log = logging.getLogger(__name__)

load_dotenv()

# noqa
# async def async_check_weather(location: str) -> str:
#     """Return the weather forecast for the specified location."""
#     log.debug(f"check_weather called with location: {location}")
#     await asyncio.sleep(10)  # Add 10 second delay (non-blocking)
#     return {"weather": "sunny", "temperature": 70}


def check_weather(location: str) -> str:
    """Return the weather forecast for the specified location."""
    log.debug(f"check_weather called with location: {location}")
    time.sleep(10)  # Add 10 second delay (blocking)
    return {"weather": "sunny", "temperature": 70}


client = ChatOpenAI(
    model="gpt-4.1-2025-04-14",
    temperature=0,
    max_tokens=None,
)


async def entrypoint(ctx: JobContext):
    await ctx.connect()

    graph = create_react_agent(
        client,
        tools=[check_weather],
        prompt="You are a helpful assistant. When calling a tool always explain what you are doing before hand.",
    )

    session = AgentSession(
        vad=silero.VAD.load(),
        stt=deepgram.STT(model="nova-3"),
        llm=openai.LLM(model="gpt-4o-mini"),
        tts=elevenlabs.TTS(),
        preemptive_generation=True,
    )

    await session.start(agent=Agent(instructions="", llm=langchain.LLMAdapter(graph)), room=ctx.room)
    await session.generate_reply(instructions="greet the user and ask them about their location so you can check the weather for them")


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
