from __future__ import annotations

from livekit import agents, rtc
from livekit.agents import AgentSession, Agent, JobContext, function_tool, cli, WorkerOptions, RoomInputOptions,RoomOutputOptions
from livekit.plugins import (
    openai,
    
    silero,
    bey,
    noise_cancellation,
    assemblyai,
)

from dotenv import load_dotenv
from pathlib import Path
from typing import List
import logging
import os
import asyncio
import json

from openai import AsyncOpenAI
import psycopg2
from pgvector.psycopg2 import register_vector
from datetime import datetime
import json
import asyncpg

import multiprocessing as mp
import asyncio
from typing import Optional


_TOOL_LOCKS: dict[str, asyncio.Lock] = {}
_TOOL_RESULTS: dict[str, str] = {}
_TOOL_LOCKS_LOCK = asyncio.Lock()  # protects _TOOL_LOCKS creation
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

load_dotenv()

# --- NEW RAG IMPLEMENTATION ---
# Database and OpenAI configuration
PG_CONN_STRING = os.getenv("PG_CONN", "postgresql://voiceaiagent:voiceagent@192.168.1.12:5433/postgres")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", None)

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set in the environment variables.")

# client = AsyncOpenAI(api_key=OPENAI_API_KEY)
async def get_id_by_email(email:str)-> int|None:
    if not email:
        return None

    conn=None
    try:
         conn = await asyncpg.connect(PG_CONN_STRING)
         row=await conn.fetchrow("SELECT id FROM users WHERE email = $1 LIMIT 1", email)
         if row:
             return row['id']
         return None
    except Exception as e:
        logging.error("Error fetching user id for email %s: %s", email, e, exc_info=True)
        return None
    finally:
        if conn:
            await conn.close()


async def get_embeddings(text: str, model="text-embedding-3-small") -> List[float] | None:
    """Generates embeddings for a given text using OpenAI."""
    text = text.replace("\n", " ")
    client=None
    try:
        client = AsyncOpenAI(api_key=OPENAI_API_KEY)
        resp = await client.embeddings.create(input=[text], model=model)
        return resp.data[0].embedding
    except Exception as e:
        logger.error(f"Error getting embeddings: {e}")
        return None
    finally:
        if client:
            await client.close()

    
# This function is now PURELY synchronous. It only does the database part.
# def query_db_for_chunks_sync(embedding: List[float], job_role_filter: str, top_k: int = 10) -> List[str]:

#     """
#     Synchronous function to query the database with a pre-computed embedding.
#     """
#     if not embedding:
#         print("No embedding provided to database query function.")
#         return []

#     conn = None
#     try:
#         conn = psycopg2.connect(PG_CONN_STRING)
#         register_vector(conn)
#         rows = []
#         with conn.cursor() as cur:
#             sql = """
#                 SELECT
#                     dc.chunk_text
#                 FROM
#                     document_chunks dc
#                 JOIN
#                     documents d ON dc.document_id = d.id
#                 WHERE
#                     d.job_role = %s
#                 ORDER BY
#                     dc.embedding <-> %s::vector
#                 LIMIT %s;
#             """
#             cur.execute(sql, (job_role_filter, embedding, top_k))
#             rows = cur.fetchall()
#             return [row[0] for row in rows]
#     except Exception as e:
#         print(f"Database query failed: {e}")
#         return []
#     finally:
#         if conn:
#             conn.close()
async def dump_running_tasks(why: Optional[str] = None) -> None:
    try:
        current=asyncio.current_task()
    except RuntimeError:
        current=None
    #snapshot of all tasks right now
    tasks=[t for t in asyncio.all_tasks() if t is not current and not t.done()]
    if why:
        logger.info("[task-dump] Reason: %s", why)
    logger.info("[task-dump] %d running task(s) found", len(tasks))
    for idx,t in enumerate(tasks,1):
        name=t.get_name() if hasattr(t,"get_name") else "<no-name>"
        coro=t.get_coro()
        coro_name=getattr(coro, "__name__", coro.__class__.__name__)
        try:
            code = getattr(coro, "cr_code", None)
            file = code.co_filename if code else "<unknown>"
            line = code.co_firstlineno if code else -1
        except Exception:
             file, line = "<unknown>", -1
        logger.info(
            "[task-dump][%d] name=%r state=%s coro=%s at %s:%s",
            idx, name, ("pending" if not t.done() else "done"), coro_name, file, line
        )
        #capture and log the stack
        try:
            frames = t.get_stack(limit=20)  # Python 3.10+
            if not frames:
                logger.info("[task-dump][%d] (no stack frames; likely awaiting I/O)", idx)
            else:
                logger.info("[task-dump][%d] Stack (top is most recent):", idx)
                for f in frames:
                    logger.info("  %s:%d in %s", f.f_code.co_filename, f.f_lineno, f.f_code.co_name)
        except Exception as e:
            logger.warning("[task-dump][%d] Could not get stack: %s", idx, e)


async def _dump_series(label: str) -> None:
    """Emit multiple snapshots: now, +1s, +2s."""
    await dump_running_tasks(f"{label}")
    await asyncio.sleep(1.0)
    await dump_running_tasks(f"{label}+1s")
    await asyncio.sleep(1.0)
    await dump_running_tasks(f"{label}+2s")

_AVATAR_ID_HINTS = ("bey", "avatar") 
_avatar_present:bool=False

# def _is_avatar(participant)->bool:
#      pid = (getattr(participant, "identity", "") or "").lower()
#      return any(tag in pid for tag in _AVATAR_ID_HINTS)

# async  def _route_audio_to_room(session: AgentSession) -> None:
#     """
#     Publish the agent's audio directly to the LiveKit room.
#     """
#     try:
#         session.output.set_audio_enabled(True)
#         logger.info("Audio routing to room established.")
#     except Exception as e:
#         logger.error(f"Failed to route audio to room: {e}")

# async def _route_audio_to_avatar(session:AgentSession):
#     """
#     Disable direct room audio; the avatar will speak for the agent.
#     """
#     try:
#         session.output.set_audio_enabled(False)
#         logger.info("Audio routing to avatar established.")
#     except Exception as e:
#         logger.error(   f"Failed to route audio to avatar: {e}")

# async def _sync_route(session: AgentSession) -> None:
#     """
#     Ensure routing matches current avatar presence.
#     """
#     if _avatar_present:
#         await _route_audio_to_avatar(session)
#     else:
#         await _route_audio_to_room(session)



 #NEW: Add this function to retrieve ALL chunks for a job role
def find_all_chunks_for_role(job_role_filter: str) -> List[str]:
    """
    Retrieves ALL document chunks for a given job role (no vector search).
    Use this when you want to extract all questions from all documents.
    """
    conn = None
    try:
        conn = psycopg2.connect(PG_CONN_STRING)
        register_vector(conn)
        
        with conn.cursor() as cur:
            sql = """
                SELECT
                    dc.chunk_text
                FROM
                    document_chunks dc
                JOIN
                    documents d ON dc.document_id = d.id
                WHERE
                    d.job_role = %s
                ORDER BY
                    d.id, dc.id;
            """
            cur.execute(sql, (job_role_filter,))
            rows = cur.fetchall()
            return [row[0] for row in rows]
    except Exception as e:
        logger.error(f"Database query failed: {e}")
        return []
    finally:
        if conn:
            conn.close()
        
async def generate_questions_from_context(query: str, job_role: str) -> str:
    """
    Retrieves ALL chunks for a job role and extracts ALL questions.
    """
    logger.info(f"Retrieving all chunks for role: '{job_role}'")

    # Get ALL chunks instead of using vector search
    all_chunks = await asyncio.to_thread(find_all_chunks_for_role, job_role)

    if not all_chunks:
        return "Could not find any documents for this job role."

    context = "\n---\n".join(all_chunks)
    
    # UPDATED PROMPT: Emphasizes extracting ALL questions
    prompt = f"""
You are a precise data extraction assistant. Your task is to extract ALL Multiple-Choice Questions (MCQs) and ALL Subjective Questions from the provided context.

Follow these rules strictly:

1. **Extract EVERY Question:** 
   - Extract ALL MCQs and ALL Subjective Questions found in the context
   - Do not skip any questions
   - Do not limit yourself to any specific number
   - Extract them in the order they appear in the context

2. **Identify Both Types:**
   - An **MCQ** consists of a question statement followed by a list of options (e.g., a, b, c, d).
   - A **Subjective Question** is an open-ended question requiring an explanation.

3. **Extract Verbatim:** 
   - Extract questions and their options EXACTLY as they appear
   - Do not rephrase, summarize, or modify the text
   - Preserve original spelling, even if incorrect (e.g., "Commanly")

4. **Strict Output Format:**

   **For MCQ Questions:**
   ```
   ## Multiple-Choice Questions
   1. [Question text]__________
   a) [Option A text]
   b) [Option B text]
   c) [Option C text]
   d) [Option D text]
   **Answer:** [correct option letter]
   ```

   **For Subjective Questions:**
   ```
   ## Subjective Questions
   1. [Question text]
   **Answer:** [Answer text]
   ```

5. **Format Rules:**
   - Each MCQ must have exactly 10 underscores (__________) after the question text
   - Options must be labeled as a), b), c), d) with a space after the closing parenthesis
   - Answer must be on a new line with bold formatting: **Answer:**
   - Number questions sequentially within each section starting from 1
   - Maintain original text formatting and line breaks

6. **Important:**
   - Extract ALL questions, regardless of how many there are
   - If you find 50 MCQs and 20 subjective questions, extract all 70
   - Maintain the exact wording from the source

CONTEXT:
---
{context}
---

EXTRACTED QUESTIONS (Extract ALL questions found):
"""
    client=None
    try:
        client = AsyncOpenAI(api_key=OPENAI_API_KEY)
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            temperature=0,  # Added for consistency
            seed=42,        # Added for reproducibility
            messages=[
                {"role": "system", "content": "You are an assistant that extracts ALL complete multiple-choice and subjective questions from text without any filtering or selection."},
                {"role": "user", "content": prompt}
            ]
        )
        return response.choices[0].message.content
    except Exception as e:
        logger.error(f"Error generating questions: {e}")
        return f"An error occurred while generating questions: {e}"
    finally:
        # CRITICAL: Always close the client
        if client:
            await client.close()
# # replace these
# # _TOOL_LOCKS: dict[str, asyncio.Lock] = {}
# # _TOOL_RESULTS: dict[str, str] = {}
# # _TOOL_TASKS: dict[str, asyncio.Task] = {}

# # def _cache_key(job_role: str, room_name: str | None) -> str:
# #     return f"{job_role}::{room_name or 'unknown_room'}"

# # async def generate_questions_from_context(query: str, job_role: str, room_name: str | None = None) -> str:
# #     key = _cache_key(job_role, room_name)

# #     # return cached text immediately
# #     if key in _TOOL_RESULTS:
# #         logger.info("Returning cached questions for %s", key)
# #         return _TOOL_RESULTS[key]

# #     # if a task is already running, await it (no extra locks)
# #     if key in _TOOL_TASKS:
# #         return await _TOOL_TASKS[key]

# #     async def _work():
# #         all_chunks = await asyncio.to_thread(find_all_chunks_for_role, job_role)
# #         if not all_chunks:
# #             return "Could not find any documents for this job role."

# #         context = "\n---\n".join(all_chunks)
# #         prompt =f"""
# #     You are a precise data extraction assistant. Your task is to extract ALL Multiple-Choice Questions (MCQs) and ALL Subjective Questions from the provided context.

# #     Follow these rules strictly:

# #     1. **Extract EVERY Question:** 
# #     - Extract ALL MCQs and ALL Subjective Questions found in the context
# #     - Do not skip any questions
# #     - Do not limit yourself to any specific number
# #     - Extract them in the order they appear in the context

# #     2. **Identify Both Types:**
# #     - An **MCQ** consists of a question statement followed by a list of options (e.g., a, b, c, d).
# #     - A **Subjective Question** is an open-ended question requiring an explanation.

# #     3. **Extract Verbatim:** 
# #     - Extract questions and their options EXACTLY as they appear
# #     - Do not rephrase, summarize, or modify the text
# #     - Preserve original spelling, even if incorrect (e.g., "Commanly")

# #     4. **Strict Output Format:**

# #     **For MCQ Questions:**
# #     ```
# #     ## Multiple-Choice Questions
# #     1. [Question text]__________
# #     a) [Option A text]
# #     b) [Option B text]
# #     c) [Option C text]
# #     d) [Option D text]
# #     **Answer:** [correct option letter]
# #     ```

# #     **For Subjective Questions:**
# #     ```
# #     ## Subjective Questions
# #     1. [Question text]
# #     **Answer:** [Answer text]
# #     ```

# #     5. **Format Rules:**
# #     - Each MCQ must have exactly 10 underscores (__________) after the question text
# #     - Options must be labeled as a), b), c), d) with a space after the closing parenthesis
# #     - Answer must be on a new line with bold formatting: **Answer:**
# #     - Number questions sequentially within each section starting from 1
# #     - Maintain original text formatting and line breaks

# #     6. **Important:**
# #     - Extract ALL questions, regardless of how many there are
# #     - If you find 50 MCQs and 20 subjective questions, extract all 70
# #     - Maintain the exact wording from the source

# #     CONTEXT:
# #     ---
# #     {context}
# #     ---

# #     EXTRACTED QUESTIONS (Extract ALL questions found):
# #     """  # your existing prompt string builder

# #         client = AsyncOpenAI(api_key=OPENAI_API_KEY)
# #         try:
# #             resp = await asyncio.wait_for(
# #                 client.chat.completions.create(
# #                     model="gpt-4o-mini",
# #                     temperature=0,
# #                     seed=42,
# #                     messages=[{"role":"system","content":"You are an assistant..."}, {"role":"user","content": prompt}],
# #                 ),
# #                 timeout=25,  # tighter
# #             )
# #             out = resp.choices[0].message.content
# #             _TOOL_RESULTS[key] = out
# #             return out
# #         finally:
# #             await client.close()

# #     task = asyncio.create_task(_work())
# #     _TOOL_TASKS[key] = task
# #     try:
# #         return await task
# #     finally:
# #         _TOOL_TASKS.pop(key, None)

# async def generate_questions_from_context(query: str, job_role: str) -> str:
#     logger.info(f"Retrieving all chunks for role: '{job_role}'")

#     # create or get a lock for this job_role
#     async with _TOOL_LOCKS_LOCK:
#         if job_role not in _TOOL_LOCKS:
#             _TOOL_LOCKS[job_role] = asyncio.Lock()
#     lock = _TOOL_LOCKS[job_role]

#     # If result cached, return it immediately (guards duplicate tool runs)
#     if job_role in _TOOL_RESULTS:
#         logger.info("Returning cached questions for job_role=%s", job_role)
#         return _TOOL_RESULTS[job_role]

#     async with lock:
#         # Double-check cache inside lock (another coroutine may have filled it)
#         if job_role in _TOOL_RESULTS:
#             return _TOOL_RESULTS[job_role]

#         # fetch all chunks (unchanged)
#         all_chunks = await asyncio.to_thread(find_all_chunks_for_role, job_role)
#         if not all_chunks:
#             return "Could not find any documents for this job role."

#         context = "\n---\n".join(all_chunks)
#         prompt = f"""
#     You are a precise data extraction assistant. Your task is to extract ALL Multiple-Choice Questions (MCQs) and ALL Subjective Questions from the provided context.

#     Follow these rules strictly:

#     1. **Extract EVERY Question:** 
#     - Extract ALL MCQs and ALL Subjective Questions found in the context
#     - Do not skip any questions
#     - Do not limit yourself to any specific number
#     - Extract them in the order they appear in the context

#     2. **Identify Both Types:**
#     - An **MCQ** consists of a question statement followed by a list of options (e.g., a, b, c, d).
#     - A **Subjective Question** is an open-ended question requiring an explanation.

#     3. **Extract Verbatim:** 
#     - Extract questions and their options EXACTLY as they appear
#     - Do not rephrase, summarize, or modify the text
#     - Preserve original spelling, even if incorrect (e.g., "Commanly")

#     4. **Strict Output Format:**

#     **For MCQ Questions:**
#     ```
#     ## Multiple-Choice Questions
#     1. [Question text]__________
#     a) [Option A text]
#     b) [Option B text]
#     c) [Option C text]
#     d) [Option D text]
#     **Answer:** [correct option letter]
#     ```

#     **For Subjective Questions:**
#     ```
#     ## Subjective Questions
#     1. [Question text]
#     **Answer:** [Answer text]
#     ```

#     5. **Format Rules:**
#     - Each MCQ must have exactly 10 underscores (__________) after the question text
#     - Options must be labeled as a), b), c), d) with a space after the closing parenthesis
#     - Answer must be on a new line with bold formatting: **Answer:**
#     - Number questions sequentially within each section starting from 1
#     - Maintain original text formatting and line breaks

#     6. **Important:**
#     - Extract ALL questions, regardless of how many there are
#     - If you find 50 MCQs and 20 subjective questions, extract all 70
#     - Maintain the exact wording from the source

#     CONTEXT:
#     ---
#     {context}
#     ---

#     EXTRACTED QUESTIONS (Extract ALL questions found):
#     """  # your existing prompt

#         client = None
#         try:
#             client = AsyncOpenAI(api_key=OPENAI_API_KEY)
#             # add a timeout so the call can't hang forever
#             response = await asyncio.wait_for(
#                 client.chat.completions.create(
#                     model="gpt-4o-mini",
#                     temperature=0,
#                     seed=42,
#                     messages=[{"role":"system","content":"You are an assistant..."}, {"role":"user","content":prompt}]
#                 ),
#                 timeout=30  # seconds; tune as needed
#             )
#             out = response.choices[0].message.content
#             # cache result so subsequent calls for same role return same content immediately
#             _TOOL_RESULTS[job_role] = out
#             return out

#         except asyncio.TimeoutError:
#             logger.error("OpenAI call timed out for job_role=%s", job_role)
#             return "An error occurred while generating questions: timeout"
#         except Exception as e:
#             logger.error(f"Error generating questions: {e}", exc_info=True)
#             return f"An error occurred while generating questions: {e}"
#         finally:
#             if client:
#                 await client.close()



# --- UPDATED FUNCTION TOOL ---

@function_tool
async def generate_questions_from_knowledge_base(query: str, job_role: str) -> str:
    """
    Generates a list of quiz questions based on a query and a job role by searching the knowledge base.
    Use this tool to get all the questions you must ask the user at once.
    """
    try:
        result = await generate_questions_from_context(query, job_role)
        logger.info(f"Tool 'generate_questions_from_knowledge_base' returned: {result}")
        # This function calls our new RAG pipeline
        return result
    except Exception as e:
        logger.error(f"Error generating questions from knowledge base: {e}")
        return f"An error occurred while trying to generate questions: {e}"

# --- UPDATED AGENT LOGIC ---

class QuizBot(Agent):
    def __init__(self, topic: str) -> None:
        # The 'topic' here is the job role (e.g., "HPLC Analyst")
        SYSTEM_PROMPT = f"""You are an automated training quiz bot for a '{topic}' role. Your behavior is strictly governed by the following rules. Do not deviate.

**Core Directive:** Your ONLY task is to administer a quiz.

**Execution Flow:**
1.  **Greeting:** Start the conversation by greeting the user and stating you will begin the quiz on the topic of '{topic}'.
2.  **One-Time Question Retrieval:** Immediately after the greeting, you MUST use the `generate_questions_from_knowledge_base` tool **exactly ONCE** and never again. Use it with these arguments:
    - `query`: "generate 10 quiz questions, including multiple-choice and subjective questions"
    - `job_role`: "{topic}"
3.  **Administer the Quiz:**
    - After the tool returns a list of questions, your ONLY job is to ask them. Read each question verbatim, one by one, in the exact order received.
    - For multiple-choice questions, read the question and then each option clearly with a small pause.
    - After asking a question, say "Please provide your answer."
    - Once the user answers, provide a neutral transition like "Okay, moving on." and ask the next question.
    - **User Interaction Rules:**
        - **If the user is confused:** If the user expresses confusion or asks you to repeat the question (e.g., "I don't understand," "Can you say that again?"), you MUST repeat the current question verbatim and then say, "Please provide your answer."
        - **If the user doesn't know:** If the user indicates they do not know the answer (e.g., "I don't know," "skip"), you MUST respond with, "Alright, it's okay. Let's move on to the next question," and then proceed immediately to the next question.
4.  **Handling No Questions:** If the tool returns a message indicating that no questions could be found or an error occurred, you MUST inform the user about the problem (e.g., "I couldn't retrieve any questions for this topic right now.") and then end the conversation.
5.  **Conclusion:** After the very last question from the list has been answered, thank the user for their time and end the session.

**Strict Prohibitions:**
- **Interruption Handling:** If the user interrupts you while you are speaking, stop talking immediately. When it's your turn to speak again, you MUST continue your previous sentence from exactly where you left off. For example, if you were saying "Question 3: Commonly used modifiers in..." and the user spoke, your next response should be "...Reversed Phase Chromatography are...".
- **DO NOT** end the conversation or disconnect until all questions have been administered, or if the question retrieval tool fails.
- **DO NOT** call the `generate_questions_from_knowledge_base` tool more than once.
- **DO NOT** invent your own questions.
- **DO NOT** provide answers, hints, or feedback on user responses.
- **DO NOT** engage in small talk.
- **IMPORTANT FOR SPEECH:** Your spoken output must be clean, plain text. Do not include markdown like asterisks (`*`).
- **if there is some external noise or interruption, do not acknowledge it.** Continue with the quiz as if nothing happened.
"""
        
        super().__init__(
            instructions=SYSTEM_PROMPT,
            tools=[generate_questions_from_knowledge_base]
        )

# --- ENTRYPOINT (Unchanged) ---
# --- ENTRYPOINT with Fixed Text Handling ---
async def entrypoint(ctx: JobContext) -> None:
    await ctx.connect()
    logger.info("Connected to LiveKit room")

    if ctx.room and ctx.room.local_participant:
        agent_identity = ctx.room.local_participant.identity
        logger.info(f"LiveKit Agent connected with ID: {agent_identity}")
    else:
          logger.warning("No local participant found for this worker.")
    
    @ctx.room.on("participant_disconnected")
    def handle_user_leave(p):
        pid = (getattr(p, "identity", "") or "").lower()

        def is_programmatic(name: str) -> bool:
            return any(tag in name for tag in ("agent", "bey", "avatar"))

        # If it's our agent or avatar, just log and bail.
        if is_programmatic(pid):
            logger.info("Programmatic participant %s disconnected; ignoring.", p.identity)
            return

        logger.info("Human participant %s disconnected; evaluating shutdown...", p.identity)

        async def maybe_shutdown():
            # Grace period to allow quick reconnects / network hiccups
            await asyncio.sleep(5.0)  # was 2.0; give avatars & clients more time

            def is_human(part) -> bool:
                name = (getattr(part, "identity", "") or "").lower()
                return not is_programmatic(name)

            remaining_humans = [rp for rp in ctx.room.remote_participants.values() if is_human(rp)]
            if remaining_humans:
                logger.info("Humans still present (%s); not shutting down.", [rp.identity for rp in remaining_humans])
                return

            logger.info("No human participants remain; initiating shutdown.")
            try:
                ctx.shutdown(reason=f"{p.identity} left")
            except Exception as e:
                logger.error("Error during shutdown after participant disconnect: %s", e)

        asyncio.create_task(maybe_shutdown(), name="maybe_shutdown_after_disconnect")


    
    def on_participant_connected(participant):
        nonlocal session
        logger.info("Participant connected: %s", participant.identity)
       
    department = "HPLC Analyst"  # A fallback
    user_participant = None
    # def on_participant_disconnected(participant):
    #     # logger.warning("Participant disconnected: %s (%s)", participant.identity, reason)
    #     # Some SDK builds expose disconnect_reason as an attribute; guard just in case
    #     reason = getattr(participant, "disconnect_reason", None)
    #     logger.warning(
    #         "Participant disconnected: %s%s",
    #         participant.identity,
    #         f" (reason={reason})" if reason else ""
    #     )
    #     try:
    #         loop = asyncio.get_running_loop()
    #         loop.create_task(_dump_series("participant_disconnected"), name="dump_on_disconnect_series")
    #     except RuntimeError:
    #         asyncio.create_task(_dump_series("participant_disconnected"), name="dump_on_disconnect")
        
       


    
        
    # participant_disc_cb = on_participant_disconnected
    participant_conn_cb = on_participant_connected
 

    # ctx.room.on("participant_disconnected", participant_disc_cb)
    ctx.room.on("participant_connected", participant_conn_cb)
    
 




    if ctx.room.remote_participants:
        user_participant = list(ctx.room.remote_participants.values())[0]
        logger.info(f"Found remote participant: {user_participant.identity}")

    if user_participant and user_participant.metadata:
        try:
            metadata = json.loads(user_participant.metadata)
            department = metadata.get("department", "Default Department")
            current_user_email = metadata.get("loggedin_user", "unknown")
            #fetch user id from postgres
            user_id=await get_id_by_email(current_user_email)
            logger.info(f"Here is the user id :{user_id}")
            if user_id is not None:
                logger.info(f"Found DB user_id: {user_id} for email {current_user_email}")
            else:
                 logger.warning(f"No DB user found for email {current_user_email}")
            logger.info(f"Successfully retrieved department from USER metadata: {department}")
            logger.info(f"Logged in user: {current_user_email}")
        except json.JSONDecodeError:
            logger.error("Failed to parse user participant metadata.")
    else:
        logger.warning("Could not find a user participant with metadata.")
    
    base_llm = openai.LLM(model="gpt-4o-mini")
    
    session = AgentSession(
        vad=silero.VAD.load(),
        turn_detection='stt',
       stt=assemblyai.STT(
            end_of_turn_confidence_threshold=0.5,
            min_end_of_turn_silence_when_confident=200,
            max_turn_silence=1500,
        ),
       
        llm=base_llm,
        tts=openai.TTS(model="gpt-4o-mini-tts", voice="alloy"),
    )

    
    # #save the final conversation when the room closes
    # async def write_transcript_on_shutdown():
    #     ts=datetime.now().strftime("%Y%m%d_%H%M%S")
    #     room=ctx.room.name if ctx.room else "no_room"
    #     base_dir=os.path.dirname(os.path.abspath(__file__)) 
    #     # out_dir=os.environ.get("TRANSCRIPT_DIR", "/tmp")
    #     # path=os.path.join(out_dir,f"transcript_{room}_{ts}.json")
    #     #path to the backend directory
    #     backend_dir = os.path.join(base_dir, "backend")  
    #     #make sure backend directory exists
    #     os.makedirs(backend_dir, exist_ok=True)
    #     filename=f"transcript_{ts}.json"
    #     filepath=os.path.join(backend_dir,filename)
    #     answers_path=r'D:\ai_voice_project\prototype-11\backend\generated_questions\room-3a960a0d_20251028_151703.txt'

    #     # with open(filepath, "w", encoding="utf-8") as f:
    #     #     json.dump(session.history.to_dict(),f,ensure_ascii=False,indent=2)
    #     transcript_data=session.history.to_dict()
    #     from result_agent import process_interview_evaluation
    #     scoreCard=process_interview_evaluation(transcript_data,answers_path)
    #     if scoreCard and "error" not in scoreCard:
    #         print(f"[scorecard] Generated successfully")
    #         print(json.dumps(scoreCard, indent=2))
    #         conn=None
    #         try:
    #             owner_id=user_id if user_id is not None else -1
    #             #1.connect to the database
    #             conn=await asyncpg.connect(PG_CONN_STRING)
    #             #serialize the scorecard to json for the JSONB column
    #             result_json_data=json.dumps(scoreCard)
    #             #prepare and execute the insert statement
    #             insert_query="""
    #              INSERT INTO result_data (owner_id, result)
    #             VALUES ($1, $2)
    #             """
    #             #execute the insert statement by  giving the connection, query, owner_id and result_json_data
    #             await conn.execute(insert_query, owner_id, result_json_data)
    #             print(f"[database] Scorecard for owner_id {owner_id} saved successfully.")
    #         except Exception as e:
    #             print(f"[database] ERROR: Failed to save scorecard. Reason: {e}")
    #         finally:
    #             #ensure the connection is closed
    #             if conn:
    #                 await conn.close()
    #                 print("[database] Connection closed.")
    #     else:
    #          print("[scorecard] Generation failed or scorecard contains an error.")
            


        

        
    #     print(f"[transcript] saved -> {filepath}")
    #     try:
    #         logger.info("Closing agent session and releasing resources...")
    #         await session.aclose()
    #         logger.info("Agent session closed successfully.")
    #     except Exception as e:
    #         logger.error(f"Error during agent session shutdown: {e}")
    #     # finally:
    #     #     logger.info("Shutdown process completed.")
    
    # ctx.add_shutdown_callback(write_transcript_on_shutdown)
        
    # Create avatar session
    
    # global _avatar_present
    # _avatar_present = True
    # await _route_audio_to_avatar(session)

    
    avatar = bey.AvatarSession(
        avatar_id="694c83e2-8895-4a98-bd16-56332ca3f449",
        api_key=os.getenv("BEYOND_PRESENCE_API_KEY")
    )

    await avatar.start(session, room=ctx.room)
   
    
    # Start the agent session
    await session.start(
        agent=QuizBot(topic=department),
        room=ctx.room,
        room_input_options=RoomInputOptions(
            text_enabled=True,
          
            noise_cancellation=noise_cancellation.BVC(),
            close_on_disconnect=False,
            
        ),
        room_output_options=RoomOutputOptions(
            audio_enabled=False
        )
    )
    await session.say("Hello! Welcome to your training quiz session.")
    logger.info("Agent session started; voice pipeline ready")
    
    


    name="Hrishab Shetty"
    kick=await session.generate_reply(
    user_input=f"Begin the quiz for '{department}'. Greet the user and then call the tool exactly once."
)
    try:
        for attr in  ("wait_for_playback_completion", "wait", "wait_playback", "join"):
            if hasattr(kick, attr):
                await getattr(kick, attr)()
                break
    except Exception as e:
        logger.exception("Error while awaiting initial playback: %s", e)
    # wait briefly and check history
    await asyncio.sleep(1)
    try:
        logger.info("History after manual TTS: %s", session.history.to_dict().get("messages", [])[-3:])
    except Exception:
        logger.exception("Failed to read history after manual TTS")
    
    # Set up data packet handler AFTER session starts
    # This handler will receive data packets from the frontend
    # def handle_data_packet(data_packet):
    #     """Handle incoming data packets from participants"""
    #     try:
    #         # Skip if from the agent itself
    #         participant = data_packet.participant
    #         if participant and hasattr(participant, 'identity'):
    #             if 'agent' in participant.identity.lower() or 'bot' in participant.identity.lower() or 'bey' in participant.identity.lower():
    #                 logger.debug(f"Skipping data from agent: {participant.identity}")
    #                 return
            
    #         # Decode the data
    #         text = data_packet.data.decode("utf-8")
    #         logger.info(f"Received text from {participant.identity if participant else 'unknown'}: '{text}'")
    #         print(f"the users says: '{text}'")
    #         # Add the text to the session as user input
    #         # asyncio.session.generate_reply(text)
    #         # asyncio.create_task(session.generate_reply(user_input=text))
    #         # logger.info(f"Added text to session: '{text}'")
    #         handle=session.generate_reply(user_input=text)
    #         logger.info("generate_reply returned speech handle: %s", handle)
            
    #     except Exception as e:
    #         logger.error(f"Error handling data packet: {e}", exc_info=True)
    def handle_data_packet(data_packet):
             async def _process_packet(dp):
                try:
                    # Log the raw packet and participant info
                    logger.info("DATA PACKET RAW: participant=%s, kind=%s, data_len=%d",
                                getattr(dp, "participant", None),
                                getattr(dp, "kind", None),
                                len(getattr(dp, "data", b"")))
                    part = getattr(dp, "participant", None)
                    pid = getattr(part, "identity", None) if part else None
                    logger.info("DATA PACKET participant.identity: %s", pid)

                    text = dp.data.decode("utf-8") if dp.data else ""
                    logger.info("User text decoded: '%s'", text)

                    # Call generate_reply and capture the result
                    logger.info("Calling session.generate_reply(...) now")
                    handle = await session.generate_reply(user_input=text)
                    logger.info("generate_reply returned: %s", repr(handle))

                    # If handle supports waiting for playback, await it (best-effort)
                    if handle is not None:
                        # try common names for playback completion methods
                        for attr in ("wait_for_playback_completion", "wait", "wait_playback", "join"):
                            if hasattr(handle, attr):
                                logger.info("Awaiting playback via handle.%s()", attr)
                                try:
                                    await getattr(handle, attr)()
                                    logger.info("Playback wait returned successfully.")
                                except Exception as e:
                                    logger.exception("Error while awaiting handle.%s: %s", attr, e)
                                break

                    # Small pause and then dump session.history (string-limited)
                    await asyncio.sleep(0.8)
                    try:
                        hist = session.history.to_dict()
                        logger.info("Session history snapshot keys: %s", list(hist.keys())[:10])
                        # log last assistant item if present
                        msgs = hist.get("messages", []) if isinstance(hist, dict) else []
                        logger.info("Last 3 history messages (summary): %s", msgs[-3:])
                    except Exception as e:
                        logger.exception("Could not read session.history: %s", e)

                    logger.info("Finished processing data packet for text: '%s'", text)
                except Exception as exc:
                    logger.exception("Unhandled exception inside _process_packet: %s", exc)
             try:
                 asyncio.create_task(_process_packet(data_packet),name="process_data_packet")
             except RuntimeError:
                 loop=asyncio.get_event_loop()
                 loop.create_task(_process_packet(data_packet))
            
    
    # Register the data packet handler on the room
    ctx.room.on("data_received", handle_data_packet)
    logger.info("Data packet handler registered")
    # ctx.shutdown(reason="user left the room")

if __name__ == "__main__":
    mp.set_start_method('spawn', force=True)
    
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint,shutdown_process_timeout=5))