# -*- coding: utf-8 -*-
"""
Created on Mon Oct 20 10:34:54 2025

@author: LAVI
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 20 10:34:54 2025

@author: LAVI
"""

from fastapi import FastAPI, status, HTTPException, Body
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import uvicorn
import os
import asyncio
import logging
import time
from typing import Dict, Any, Optional, List
from livekit.agents import Worker, WorkerOptions, JobContext, JobRequest, cli, AgentSession, metrics, ChatContext, AgentFalseInterruptionEvent, MetricsCollectedEvent, RoomInputOptions
from livekit.agents import Agent, ChatMessage
from knowledge_utils import get_agent_context
from livekit import rtc, agents
from livekit.agents.llm import function_tool
from livekit.plugins import openai, deepgram, noise_cancellation, groq, google, elevenlabs, silero

#added
#from livekit import api

from dotenv import load_dotenv
from recording import RecordingManager
import os
import pathlib
import asyncio
import json
import traceback
import sys
#import cv2 #remove for tests
import uuid
import aiohttp
import jwt
from typing import Dict, Any, Optional
from datetime import datetime
from livekit_service_wrapper import LiveKitServiceWrapper
from dotenv import load_dotenv
from livekit import agents, rtc
from livekit.agents import (
    NOT_GIVEN,
    Agent,
    AgentFalseInterruptionEvent,
    AgentSession,
    JobContext,
    JobProcess,
    MetricsCollectedEvent,
    RoomInputOptions,
    RoomIO,
    RunContext,
    WorkerOptions,
    cli,
    metrics,
    ChatContext,
    AutoSubscribe
)
from livekit.agents.llm import function_tool
### New Addition ###
from livekit import api  # add this import
from contextlib import asynccontextmanager
import contextlib  # <-- NEW for graceful shutdown wrappers

#import pkg_resources

# Configure logging (keep a single basicConfig)
#logging.basicConfig(level=logging.INFO)
logging.basicConfig(
    level=logging.INFO,                           # show INFO and above
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
    handlers=[logging.StreamHandler(sys.stdout)],  # <-- force stdout
    force=True,  # <-- CHANGED: override uvicorn/Cloud Run handlers so your logs show
)
logger = logging.getLogger(__name__)

env_file = os.getenv('ENV_FILE', '.env.local')
if os.path.exists(env_file):
    load_dotenv(env_file, override=False)
    logger.info(f"Environment file {env_file} loaded successfully")
    # logger.info(f"Environment variables: {os.environ}")
else:
    logger.info(f"Environment file {env_file} not found, using system environment variables")
    

LK_URL = os.getenv("LIVEKIT_URL")
LK_KEY = os.getenv("LIVEKIT_API_KEY")
LK_SECRET = os.getenv("LIVEKIT_API_SECRET")
AGENT_NAME = os.getenv("AGENT_NAME", "danika-agent")


#New Addition

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 1) LiveKit API client (async context => loop exists)
    app.state.lkapi = api.LiveKitAPI(url=LK_URL, api_key=LK_KEY, api_secret=LK_SECRET)
    logger.info("✅ LiveKitAPI client created in lifespan")

    # 2) Start the Worker here (same app instance, same loop)
    if not (LK_URL and LK_KEY and LK_SECRET):
        raise RuntimeError("LIVEKIT_URL / LIVEKIT_API_KEY / LIVEKIT_API_SECRET are required")

    logger.info("🔧 Starting LiveKit Worker…")
    logger.info(f"AGENT_NAME for WorkerOptions: {AGENT_NAME}")

    opts = WorkerOptions(
        entrypoint_fnc=entrypoint,
        prewarm_fnc=prewarm,
        agent_name=AGENT_NAME,
        ws_url=LK_URL,
        api_key=LK_KEY,
        api_secret=LK_SECRET,
        # optional while debugging:
        #num_processes=1,
    )
    app.state.worker = Worker(opts)
    worker_task = asyncio.create_task(app.state.worker.run())
    logger.info("✅ LiveKit Worker task scheduled")

    try:
        yield
    finally:
        # orderly shutdown
        logger.info("🛑 Shutting down worker & LiveKitAPI")
        with contextlib.suppress(Exception):
            if hasattr(app.state.worker, "aclose"):
                await app.state.worker.aclose()
            elif hasattr(app.state.worker, "close"):
                await app.state.worker.close()
        with contextlib.suppress(Exception):
            if hasattr(app.state.lkapi, "aclose"):
                await app.state.lkapi.aclose()
            elif hasattr(app.state.lkapi, "close"):
                app.state.lkapi.close()


app = FastAPI(lifespan=lifespan)

#END

#app = FastAPI()
"""
SKIP_LK_API_INIT = os.getenv("SKIP_LK_API_INIT", "0") == "1"
if not SKIP_LK_API_INIT:
    app.state.lkapi = api.LiveKitAPI(url=LK_URL, api_key=LK_KEY, api_secret=LK_SECRET)
else:
    app.state.lkapi = None

app.state.worker = None
"""
### New Addition ###
#app.state.lkapi = None
### END ###
"""
@app.on_event("startup")
async def start_worker():
    logger.info("🔧 Starting LiveKit Worker…")
    logger.info(f"AGENT_NAME for WorkerOptions: {AGENT_NAME}")
    if not (LK_URL and LK_KEY and LK_SECRET):
        raise RuntimeError("LIVEKIT_URL / LIVEKIT_API_KEY / LIVEKIT_API_SECRET are required")

    opts = WorkerOptions(
        entrypoint_fnc=entrypoint,   # your existing function
        prewarm_fnc=prewarm,         # your existing function (optional)
        agent_name=AGENT_NAME,       # STABLE name for explicit dispatch
        ws_url=LK_URL,
        api_key=LK_KEY,
        api_secret=LK_SECRET,
    )
    app.state.worker = Worker(opts)
    asyncio.create_task(app.state.worker.run())

@app.on_event("shutdown")
async def close_api():
    # NEW: close worker and lkapi deterministically
    if getattr(app.state, "worker", None):
        with contextlib.suppress(Exception):
            if hasattr(app.state.worker, "close") and callable(app.state.worker.close):
                await app.state.worker.close()
            elif hasattr(app.state.worker, "aclose") and callable(app.state.worker.aclose):
                await app.state.worker.aclose()
    if app.state.lkapi:
        with contextlib.suppress(Exception):
            await app.state.lkapi.aclose()
### END ###
"""



# Check specific critical variables
critical_vars = ['LIVEKIT_API_SECRET', 'LIVEKIT_API_KEY', 'LIVEKIT_URL', 'PORT']
for var in critical_vars:
    value = os.environ.get(var)
    if value:
        logger.info(f"✓ {var} is set")
    else:
        logger.warning(f"✗ {var} is NOT set!")


#SKIP_VAD = os.getenv("SKIP_VAD", "1") == "1"   # default: skip in prod
SKIP_VAD = 1
def prewarm(proc: JobProcess):
    logger.info("################### setting VAD ####################")
    proc.userdata["vad"]= None
    if SKIP_VAD:
        logger.info("Skipping VAD prewarm (SKIP_VAD=1)")
        return
    try:
        start = time.time()
        proc.userdata["vad"] = silero.VAD.load()
        logger.info(f"VAD initialized successfully in {time.time()-start:.2f}s")
    except Exception as e:
        logger.error(f"Failed to initialize VAD: {e}")
        # don't raise; we can run without VAD
        # raise



# Add CORS middleware to allow requests from your frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, replace "*" with your frontend domain
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class Assistant(Agent):
    def __init__(self, chat_ctx: ChatContext = None, instructions: str = None):
        super().__init__(chat_ctx=chat_ctx, instructions=instructions)
    
    async def on_text(self, text, ctx):
        # Add debug logging for text input
        logger.debug(f"Received text input: {text}")
        return await super().on_text(text, ctx)
    
    async def on_audio(self, audio_data, ctx):
        # Add debug logging for audio input
        logger.debug(f"Received audio input: {len(audio_data)} bytes")
        # Process the audio through the parent class
        return await super().on_audio(audio_data, ctx)
        
    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
        # Callback before generating a reply after user turn committed
        if not new_message.text_content:
            # Ignore empty user turns
            logger.info("Ignoring empty user turn")
            raise agents.StopResponse()

# Pydantic models for request/response validation
class JoinRoomRequest(BaseModel):
    room_name: str = Field(..., description="Name of the room to join")
    agent_name: str = Field(..., description="Name of the agent joining the room")

class AgentResponse(BaseModel):
    status: str
    message: str
    room: Optional[str] = None
    agent: Optional[str] = None
    agent_id: Optional[str] = None

# Dictionary to store active job contexts by room name
_active_agents: Dict[str, JobContext] = {}

# Lock for thread-safe operations on _active_agents
import threading
_agents_lock = threading.Lock()

@app.get("/active-agents")
async def list_active_agents():
    """List all currently active agents and their rooms."""
    with _agents_lock:
        return {
            "status": "success",
            "count": len(_active_agents),
            "agents": [
                {
                    "agent_id": agent_id,
                    "room": getattr(ctx, "room_name", None),
                    "participant_name": getattr(ctx, "participant_name", None),
                    "connected": getattr(getattr(ctx, "room", None), "is_connected", lambda: False)()
                }
                for agent_id, ctx in _active_agents.items()
            ]
        }

# NEW: shared graceful shutdown procedure with timeouts
async def _graceful_shutdown(ctx, session, room_io, recording_manager):
    # 1) stop any ongoing generation quickly
    with contextlib.suppress(Exception):
        if hasattr(session, "stop"):
            await asyncio.wait_for(session.stop(), timeout=3)
    # 2) close session (kills TTS/STT/VAD workers)
    with contextlib.suppress(Exception):
        if hasattr(session, "aclose"):
            await asyncio.wait_for(session.aclose(), timeout=5)
    # 3) stop RoomIO loop (unsubscribe / cancel reader tasks)
    with contextlib.suppress(Exception):
        if room_io is not None and hasattr(room_io, "stop"):
            await asyncio.wait_for(room_io.stop(), timeout=3)
    # 4) stop recording
    with contextlib.suppress(Exception):
        if recording_manager is not None:
            await asyncio.wait_for(recording_manager.stop_recording(), timeout=5)
            await asyncio.wait_for(recording_manager.close(), timeout=3)
    # 5) disconnect room last
    with contextlib.suppress(Exception):
        if getattr(ctx, "room", None) and ctx.room.is_connected():
            await asyncio.wait_for(ctx.room.disconnect(), timeout=5)

def _room_connected(room) -> bool:
    try:
        return getattr(room, "connection_state", None) == rtc.ConnectionState.CONNECTED
    except Exception:
        return False


@app.post("/leave-room/{agent_id}")
async def leave_room(agent_id: str):
    """Make a specific agent leave its room deterministically."""
    with _agents_lock:
        ctx = _active_agents.pop(agent_id, None)
    if not ctx:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"No active agent found with ID {agent_id}"
        )

    # Prefer the framework-provided shutdown when available
    if hasattr(ctx, "shutdown") and callable(ctx.shutdown):
        await ctx.shutdown()
        return {
            "status": "success",
            "message": f"Agent {agent_id} shutdown requested",
            "agent_id": agent_id,
            "room": getattr(getattr(ctx, "room", None), "name", "unknown"),
        }

    # Fallback: perform the same cleanup path manually
    try:
        await _graceful_shutdown(ctx, getattr(ctx, "_session", None), getattr(ctx, "_room_io", None), getattr(ctx, "_recording_manager", None))
    except Exception:
        pass

    return {
        "status": "success",
        "message": f"Agent {agent_id} disconnected",
        "agent_id": agent_id,
        "room": getattr(getattr(ctx, "room", None), "name", "unknown"),
    }

@app.get("/health")
async def health_check():
    """Health check endpoint that returns a 200 status code when the service is running."""
    try:
        logger.info("Health check endpoint called")
        return JSONResponse(
            status_code=200,
            content={
                "status": "ok",
                "service": "danika-ai-agent",
                "version": os.getenv("SERVICE_VERSION", "1.0.0")
            }
        )
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={"status": "error", "message": str(e)}
        )

async def entrypoint(ctx: JobContext):
    """Main entrypoint for the agent."""
    agent_id = None
    recording_manager = None
    room = None
    livekit_service = None
    user_id = None
    logger.info('========== AGENT ENTRY FUNCTION STARTED ===========')

    try:
        # Validate room context
        if not hasattr(ctx, 'room') or not ctx.room:
            raise ValueError("Room not available in job context")
        
        room = ctx.room
        room_name = getattr(room, 'name', 'unknown')
        if not room_name or room_name == 'unknown':
            raise ValueError("Room name not provided in worker userdata")
        
        
        # Connect to the room
        logger.info("[entrypoint] calling ctx.connect(auto_subscribe=AUDIO_ONLY) …")
        await ctx.connect()#(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
        
        presenter_identity: Optional[str] = None
        
        def _dump_track_pubs(tag=""):
            for identity, rp in ctx.room.remote_participants.items():
                for sid, pub in rp.track_publications.items():
                    try:
                        logger.info(
                            f"[PUB {tag}] {identity} sid={sid} "
                            f"source={pub.source} kind={getattr(pub,'kind',None)} "
                            f"subscribed={getattr(pub,'subscribed',None)} "
                            f"muted={getattr(pub,'muted',None)} "
                            f"disabled={getattr(pub,'disabled',None)} "
                            f"track_is_muted={getattr(getattr(pub,'track',None),'muted',None)}"
                        )
                    except Exception:
                        pass
        
        @ctx.room.on("track_published")
        def _on_track_published(publication, participant):
            logger.info(f"[SFU] track_published by {participant.identity} src={publication.source}")
            _dump_track_pubs("published")
        
        
         # --- SFU sanity logs ---
        @ctx.room.on("active_speakers_changed")
        def _on_active_speakers_changed(speakers: list[rtc.Participant]):
            ids = [getattr(p, "identity", "?") for p in speakers]
            logger.info(f"[SFU] active_speakers_changed -> {ids}")
        
        @ctx.room.on("participant_speaking_changed")
        def _on_participant_speaking_changed(p: rtc.Participant):
            logger.info(f"[SFU] speaking_changed: {p.identity} speaking={getattr(p,'is_speaking',False)}")
       
        # ---- mic subscription waiter ----
        mic_waiters: Dict[str, asyncio.Future] = {}
        """
        @ctx.room.on("track_subscribed")
        def _on_track_subscribed(track, publication, participant):
            if publication.source == rtc.TrackSource.SOURCE_MICROPHONE:
                logger.info(f"[AGENT] Subscribed to MIC from {participant.identity} / sid={publication.sid}")
                fut = mic_waiters.get(participant.identity)
                if fut and not fut.done():
                    fut.set_result(True)
        
        @ctx.room.on("track_unsubscribed")
        def _on_track_unsubscribed(track, publication, participant):
            if publication.source == rtc.TrackSource.SOURCE_MICROPHONE:
                logger.info(f"[AGENT] Unsubscribed from MIC from {participant.identity}")
        """
        async def _wait_for_mic_subscription(identity: str, timeout: float = 10.0) -> bool:
            rp = ctx.room.remote_participants.get(identity)
            if rp:
                try:
                    if any(pub.source == rtc.TrackSource.SOURCE_MICROPHONE and getattr(pub, "subscribed", False)
                           for pub in rp.track_publications.values()):
                        return True
                except Exception:
                    pass
            fut = mic_waiters.get(identity)
            if not fut or fut.done():
                fut = asyncio.get_event_loop().create_future()
                mic_waiters[identity] = fut
            try:
                await asyncio.wait_for(fut, timeout=timeout)
                return True
            except asyncio.TimeoutError:
                return False
        # ---- end waiter ----
        """
        @ctx.room.on("track_subscribed")
        def _on_track_subscribed(track, publication, participant):
            if publication.source == rtc.TrackSource.SOURCE_MICROPHONE:
                logger.info(f"[AGENT] Subscribed to MIC from {participant.identity} / sid={publication.sid}")
        
        @ctx.room.on("track_unsubscribed")
        def _on_track_unsubscribed(track, publication, participant):
            if publication.source == rtc.TrackSource.SOURCE_MICROPHONE:
                logger.info(f"[AGENT] Unsubscribed from MIC from {participant.identity}")
        """
        
        logger.info("[entrypoint] ctx.connect() OK")
        agent_id = getattr(ctx.agent, 'identity', None)
        if not agent_id:
            raise ValueError("Failed to get agent identity")
            
        logger.info(f"Connected to room {room_name} as {agent_id}")
        
        # Store this context in active agents (just the ctx; we also purge before cleanup)
        with _agents_lock:
            _active_agents[agent_id] = ctx

        # ADDED NEW CODE HERE #
        use_service = False
        livekit_service = None
        user_id = os.getenv('USER_ID', 'default_user_id')
        logger.info("Knowledge/Instructions service DISABLED (no calls to :2040 will be made)")
        # END
        
        if (use_service):
            # Initialize the LiveKitService wrapper with the correct API URL and auth token
            logger.info('Initializing LiveKitService wrapper...')
            api_url = os.getenv('QELOS_PLUGIN_URL', 'http://127.0.0.1:2040')
            logger.info('Creating LiveKitService wrapper...')
            livekit_service = LiveKitServiceWrapper(api_base_url=api_url) 
            logger.info('LiveKitService wrapper created')
            user_id = os.getenv('USER_ID', 'default_user_id')
            
        # Load agent context (instructions and knowledge)
        context = await get_agent_context(use_service=use_service, livekit_service=livekit_service, user_id=user_id)
        logger.info(f"Loaded instructions: {context['instructions'][:50]}...")
        if context['knowledge']:
            logger.info(f"Loaded knowledge: {context['knowledge'][:50]}...")
        
        async def _cleanup():
            logger.info("Room disconnected, performing cleanup...")
            nonlocal recording_manager, agent_id
            
            try:
                # Stop any active recording
                if recording_manager is not None:
                    await recording_manager.close()
                    logger.info("Recording manager closed during disconnect")
                
                # Remove from active agents
                if agent_id:
                    with _agents_lock:
                        _active_agents.pop(agent_id, None)
                            # ensure purged early
                # Explicitly close the session if it exists
                if 'session' in locals() and session is not None:
                    try:
                        if hasattr(session, 'aclose') and callable(session.aclose):
                            await session.aclose()
                            logger.info("Agent session closed")
                        elif hasattr(session, 'close') and callable(session.close):
                            await session.close()
                            logger.info("Agent session closed (using close())")
                        else:
                            logger.warning("Session object has no aclose() or close() method")
                    except Exception as e:
                        logger.error(f"Error closing session: {e}", exc_info=True)
                    
            except Exception as e:
                logger.error(f"Error during cleanup: {e}", exc_info=True)
                
            logger.info("Cleanup completed, agent is ready for reconnection")

        def on_disconnected():
            # Schedule the async cleanup but don't exit the process
            logger.info("Room disconnected event received")
            # NEW: call the unified graceful shutdown for symmetry
            asyncio.create_task(_graceful_shutdown(ctx, getattr(ctx, "_session", None), getattr(ctx, "_room_io", None), getattr(ctx, "_recording_manager", None)))
            
        # Register the synchronous handler
        ctx.room.on("disconnected", on_disconnected)
        logger.info("Registered disconnect handler")
        
        # Initialize the agent session with the same configuration as in agent.py
        modelsNames = ["gpt-4o-mini", "whisper-1", "gpt-4o-mini-tts"]

        # --- CHANGED: load VAD here (not in prewarm), optional model path vendored into image ---
        vad = None
        try:
            start = time.time()
            model_path = os.getenv("SILERO_VAD_PATH")  # optional: point to a vendored model file
            
            #debuggin vad
            vad = silero.VAD.load(model_path=model_path) if model_path else silero.VAD.load()
            
            logger.info(f"VAD loaded in {time.time() - start:.2f}s (path={'set' if model_path else 'auto'})")
        except Exception as e:
            logger.exception("VAD load failed in entrypoint; continuing without VAD")
        # -----------------------------------------------------------------------------------------


        #debugging vad
        #vad = None
        
        # Set up the agent session with the same configuration as in agent.py
        session = AgentSession(
            llm=openai.LLM(model=modelsNames[0]),
            stt=openai.STT(model=modelsNames[1], language="he"),
            tts=openai.TTS(model=modelsNames[2]),
            vad=vad,  # <-- CHANGED: use VAD loaded here
            preemptive_generation=True,
        )
        
        # keep references on ctx for external shutdown paths
        ctx._session = session

        # start with input OFF just to be safe
        session.input.set_audio_enabled(False)
        
        # 3) create/start RoomIO
        room_io = RoomIO(session, room=ctx.room)
        await room_io.start()
        ctx._room_io = room_io
        
        # 4) NOW register room handlers that reference session/room_io
        @ctx.room.on("reconnected")
        def _on_reconnected():
            logger.info("[ROOM] reconnected -> forcing input OFF then ON after we confirm mic")
            session.input.set_audio_enabled(False)
            async def _reenable():
                ident = presenter_identity or next(iter(ctx.room.remote_participants.keys()), None)
                if ident:
                    ok = await _wait_for_mic_subscription(ident, timeout=5.0)
                    session.input.set_audio_enabled(ok)
                    logger.info(f"[ROOM] reconnected -> mic ok={ok}")
            asyncio.create_task(_reenable())
         
        
        @ctx.room.on("track_subscribed")
        def _on_track_subscribed(track, publication, participant):
            if publication.source == rtc.TrackSource.SOURCE_MICROPHONE:
                logger.info(f"[AGENT] MIC subscribed from {participant.identity} / sid={publication.sid}")
                fut = mic_waiters.get(participant.identity)
                if fut and not fut.done():
                    fut.set_result(True)
                try:
                    room_io.set_participant(participant.identity)
                except Exception:
                    pass
                session.input.set_audio_enabled(True)
                logger.info("[AGENT] session.input audio ENABLED after mic subscription")
        
        @ctx.room.on("track_unsubscribed")
        def _on_track_unsubscribed(track, publication, participant):
            if publication.source == rtc.TrackSource.SOURCE_MICROPHONE:
                logger.info(f"[AGENT] MIC unsubscribed from {participant.identity} -> disabling input")
                session.input.set_audio_enabled(False)
        
        
         
        # Set up event handlers for the session
        @session.on("agent_false_interruption")
        def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
            logger.info("False positive interruption detected, resuming...")
            session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)
        
        # Set up metrics collection
        usage_collector = metrics.UsageCollector()

        
        # Log all events for debugging
        @session.on("*")
        def _on_any_event(event_name, ev):
            logger.debug(f"Event received: {event_name}")
        
        # Log input events
        @session.on("input")
        def _on_input(event):
            logger.info(f"Input received: {event.type}")
            if hasattr(event, 'text'):
                logger.info(f"Input text: {event.text}")
            if hasattr(event, 'participant'):
                logger.info(f"Input from participant: {event.participant.identity}")
        
        # Set up shutdown callback for metrics
        async def log_usage():
            summary = usage_collector.get_summary()
            logger.info(f"Usage summary: {summary}")
        
        ctx.add_shutdown_callback(log_usage)
        
        knowledge_content = context['knowledge']
        # Create a chat context with the knowledge content
        chat_ctx = ChatContext()
        if knowledge_content:
            chat_ctx.add_message(role="assistant", content=f"Reference information:\n{knowledge_content}")
        
        instructions = context['instructions']
        # Create a RoomIO instance to manage participant selection
        
        # Start the agent session
        
        #logger.info("Using livekit-agents: " + pkg_resources.get_distribution("livekit-agents").version)
        #logger.info("RoomInputOptions: close_on_disconnect=False, video_enabled=True")
        
        await session.start(
            agent=Assistant(chat_ctx=chat_ctx, instructions=instructions),
            room_input_options=RoomInputOptions(
                #noise_cancellation=noise_cancellation.BVC(), #temporarly remove for debug
                close_on_disconnect=False,
                video_enabled=True
                # Only use valid parameters for RoomInputOptions
            )
        )
        
        
        @session.on("input_audio_started")
        def _on_input_audio_started(ev):
            logger.info("[SESSION] input_audio_started")
        
        @session.on("input_audio_stopped")
        def _on_input_audio_stopped(ev):
            logger.info("[SESSION] input_audio_stopped")
        
        @session.on("metrics_collected")
        def _on_metrics_collected(ev: MetricsCollectedEvent):
            metrics.log_metrics(ev.metrics)
            usage_collector.collect(ev.metrics)
            # stt ingestion time (seconds) if available
            dur = getattr(ev.metrics, "stt_audio_duration", None)
            if dur is not None:
                logger.info(f"[METRICS] stt_audio_duration={dur:.2f}s")

        
        
        async def _enable_listen_and_verify(presenter_identity: str):
            # pick who to listen to
            room_io.set_participant(presenter_identity)
            await asyncio.sleep(0.2)  # let the SDK bind
        
            # wait until we actually have a subscribed MIC for this participant
            ok = await _wait_for_mic_subscription(presenter_identity, timeout=10.0)
            logger.info(f"[AGENT] MIC subscribed for {presenter_identity}? {ok}")
        
            # only enable input if subscribed; otherwise disable to avoid "input stream detached"
            session.input.set_audio_enabled(ok)
            if not ok:
                logger.warning(f"[AGENT] No MIC yet for {presenter_identity}; input disabled. Will re-enable when mic arrives.")
            return ok

        
        
        # Find the presenter in the room
        #presenter_identity = None
        
        # Function to check for presenter in room metadata
        async def check_for_presenter():
            nonlocal presenter_identity
            logger.info("Checking for presenter in room metadata")
            
            # Wait a moment for room to fully connect
            await asyncio.sleep(1)
            
            # Log all participants in the room
            logger.info(f"Room has {len(ctx.room.remote_participants)} remote participants")
            
            # Check room metadata for presenter identity
            if ctx.room.metadata:
                try:
                    room_metadata = json.loads(ctx.room.metadata)
                    logger.info(f"Room metadata: {room_metadata}")
                    
                    if room_metadata.get('presenterIdentity'):
                        presenter_id = room_metadata.get('presenterIdentity')
                        logger.info(f"Found presenter in room metadata: {presenter_id}")
                        presenter_identity = presenter_id
                        return
                except Exception as e:
                    logger.error(f"Error parsing room metadata: {e}")
            
            # Log participants in the room with detailed info
            logger.info("Detailed participant information:")
            for identity, participant in ctx.room.remote_participants.items():
                logger.info(f"Participant: {identity}, name: {participant.name}")
                logger.info(f"  - Metadata: {participant.metadata if participant.metadata else 'None'}")
                
                # Check for any data attributes that might indicate presenter status
                for attr_name in dir(participant):
                    if not attr_name.startswith('_') and not callable(getattr(participant, attr_name)):
                        try:
                            attr_value = getattr(participant, attr_name)
                            if 'presenter' in str(attr_value).lower():
                                logger.info(f"  - Found potential presenter indicator: {attr_name} = {attr_value}")
                        except:
                            pass
            
            logger.warning("No presenter identity found in room metadata")
            
            # Set default presenter to first participant if no presenter found
            if not presenter_identity and ctx.room.remote_participants:
                for identity in ctx.room.remote_participants.keys():
                    if not identity.startswith('agent') and identity != agent_id:
                        presenter_identity = identity
                        logger.info(f"No presenter in metadata, using first non-agent participant as default: {presenter_identity}")
                        break
        
        
        # Keep the RPC method for setting presenter as a fallback
        # This allows manual control if needed
        @ctx.room.local_participant.register_rpc_method("set_presenter")
        async def on_set_presenter(data: rtc.RpcInvocationData) -> None:
            nonlocal presenter_identity
            target_identity = data.payload or data.caller_identity
            
            logger.info(f"set_presenter called with target: {target_identity}")
            
            presenter_identity = target_identity
            await _enable_listen_and_verify(presenter_identity)
            return {"success": True, "presenter": target_identity}
        
        # Special RPC method for local testing to force the agent to listen to a specific participant
        @ctx.room.local_participant.register_rpc_method("force_listen")
        async def on_force_listen(data: rtc.RpcInvocationData) -> None:
            target_identity = data.payload or data.caller_identity
            
            logger.info(f"force_listen called with target: {target_identity}")
            
            # Check if the target participant is in the room
            participant_found = False
            for identity, participant in ctx.room.remote_participants.items():
                if identity == target_identity:
                    participant_found = True
                    break
            
            if participant_found:
                logger.info(f"Forcing agent to listen to participant: {target_identity}")
                
                # Set the participant as the active participant for the agent
                room_io.set_participant(target_identity)
                
                # Enable audio input and ensure it's at maximum sensitivity
                session.input.set_audio_enabled(True)
                
                # Disable any filters that might be blocking audio
                try:
                    if hasattr(session.input, 'set_noise_cancellation_enabled'):
                        session.input.set_noise_cancellation_enabled(False)
                        logger.info("Disabled noise cancellation for forced listening")
                except Exception as e:
                    logger.error(f"Error configuring audio settings: {e}")
                
                return {"success": True, "listening_to": target_identity}
            else:
                logger.error(f"Cannot force listen: Participant {target_identity} not found in room")
                return {"success": False, "error": f"Participant {target_identity} not found in room"}
        
        try:
            await ctx.room.local_participant.publish_data(
                b"Agent connected",
                topic="agent-status"
            )
            await check_for_presenter()
            
            if presenter_identity:
                logger.info(f"Setting presenter as active participant: {presenter_identity}")
                
                presenter_in_room = False
                for identity, participant in ctx.room.remote_participants.items():
                    if identity == presenter_identity:
                        presenter_in_room = True
                        logger.info(f"Confirmed presenter {presenter_identity} is in the room")
                        break
                
                if presenter_in_room:
                    logger.info(f"Setting participant for RoomIO: {presenter_identity}")
                    await _enable_listen_and_verify(presenter_identity)

                    is_local_testing = os.environ.get('LOCAL_TESTING', 'false').lower() == 'true'
                    if is_local_testing:
                        logger.info("LOCAL TESTING MODE: Using special audio settings for local testing")
                        try:
                            if hasattr(session, 'vad_sensitivity'):
                                session.vad_sensitivity = 0.5
                                logger.info("Increased VAD sensitivity for local testing")
                            if hasattr(session.input, 'set_noise_cancellation_enabled'):
                                session.input.set_noise_cancellation_enabled(False)
                                logger.info("Disabled noise cancellation for local testing")
                        except Exception as e:
                            logger.error(f"Error setting up local testing mode: {e}")
                    
                    logger.info(f"Agent is now listening to presenter: {presenter_identity}")
                else:
                    logger.error(f"Presenter {presenter_identity} not found in room participants!")
                    if ctx.room.remote_participants:
                        fallback_identity = next(iter(ctx.room.remote_participants.keys()))
                        logger.info(f"Using fallback participant: {fallback_identity}")
                        await _enable_listen_and_verify(fallback_identity)
                        
            else:
                logger.warning("No presenter found in the room. Agent will not receive audio input.")
                session.input.set_audio_enabled(False)
                
                if ctx.room.remote_participants:
                    fallback_identity = next(iter(ctx.room.remote_participants.keys()))
                    logger.info(f"No presenter found, using fallback participant: {fallback_identity}")
                    await _enable_listen_and_verify(fallback_identity)

        except Exception as e:
            logger.error(f"Error connecting to room: {e}")
            import traceback as tb
            tb.print_exc()

        # Initialize recording manager
        recording_manager = RecordingManager()
        ctx._recording_manager = recording_manager  # keep reference
        recording_id = None

        try:
            # Start recording the room
            recording_id = await recording_manager.start_recording(ctx.room.name, modelsNames)
            if recording_id:
                logger.info(f"Started recording with ID: {recording_id}")
            else:
                logger.warning("Failed to start recording")
        except Exception as e:
            logger.error(f"Error starting recording: {e}")

        # Add shutdown callback to stop recording when session ends
        async def cleanup():
            if recording_id:
                logger.info("Stopping recording...")
                await recording_manager.stop_recording()
            await recording_manager.close()
            logger.info("Cleanup completed")
        
        ctx.add_shutdown_callback(cleanup)

        # NEW: register unified graceful shutdown as the primary job shutdown path
        ctx.add_shutdown_callback(lambda: _graceful_shutdown(ctx, session, room_io, recording_manager))
    
        # Generate initial greeting
        logger.info("Generating initial greeting...")
        try:
            await session.generate_reply(
                instructions="תברך את המשתמש עם השם שלו בשפה העברית בלבד. ואז תגיד : אני דניקה. מוזר קצת לדבר עם אפליקציה, נכון? אל תדאג\י. אני כאן כדי להקשיב, לשאול ובסוף גם לערוך. תחשוב\י על זה כמו שיחה, לא כמו צילומים. מוכן\ה להתחיל?.",
            )
            logger.info("Initial greeting generated successfully")
        except Exception as e:
            logger.error(f"Error generating initial greeting: {e}")
            import traceback as tb
            tb.print_exc()
            
        if presenter_identity:
            logger.info(f"Agent is listening to presenter: {presenter_identity}")
        else:
            logger.info("No presenter detected. Agent will listen to the first participant who speaks.")
        
        await ctx.room.local_participant.publish_data(
            b"Agent connected",
            topic="agent-status"
        )

        # Safer idle loop that exits on session/room/registry changes
        try:
            while True:
                with _agents_lock:
                    still_active = agent_id in _active_agents and _active_agents.get(agent_id) is ctx
                if not still_active:
                    break
                if not getattr(ctx, "room", None) or not _room_connected(ctx.room):
                    break
                if hasattr(session, "is_closed") and getattr(session, "is_closed"):
                    break
                await asyncio.sleep(0.5)
        except asyncio.CancelledError:
            logger.info(f"Agent {agent_id} was cancelled")
        except Exception as e:
            logger.error(f"Error in agent {agent_id}: {str(e)}", exc_info=True)
        finally:
            # Purge from active agents BEFORE cleanup to avoid keeping references
            if agent_id:
                with _agents_lock:
                    _active_agents.pop(agent_id, None)

            # Perform the same orderly shutdown to avoid hangs
            try:
                await _graceful_shutdown(ctx, session, room_io, recording_manager)
            except Exception as e:
                logger.error(f"Error during final graceful shutdown: {e}", exc_info=True)
            
    except Exception as e:
        logger.error(f"Error in agent entrypoint: {str(e)}", exc_info=True)
        raise  # Re-raise the exception after logging

### New Addition ###

### NEW: helper to wait until the agent is visible in the room
async def _wait_for_agent_in_room(room_name: str, agent_name: str, timeout_s: int = 120) -> Optional[str]:
    start = asyncio.get_event_loop().time()
    an = (agent_name or "").lower()

    while (asyncio.get_event_loop().time() - start) < timeout_s:
        try:
            resp = await app.state.lkapi.room.list_participants(
                api.ListParticipantsRequest(room=room_name)
            )
            for p in resp.participants:
                ident = (getattr(p, "identity", "") or "")
                name  = (getattr(p, "name", "") or "")
                meta  = (getattr(p, "metadata", "") or "")

                il = ident.lower()
                nl = name.lower()
                ml = meta.lower()

                if (
                    il == an or nl == an or
                    il.startswith(an) or nl.startswith(an) or
                    il.startswith("agent-") or            # <<— NEW: accept generic agent identity
                    "agent" in ml or "bot" in ml
                ):
                    return ident or name
        except Exception as e:
            logger.warning(f"wait_for_agent: list_participants error: {e}")

        await asyncio.sleep(1.0)

    return None



@app.post("/join-room")
async def join_room_endpoint(request: JoinRoomRequest):
    ########### ADDED FOR TESTS ##########
    logger.info("--- LiveKit Key Configuration Check ---")
    logger.info(f"LIVEKIT_URL: {LK_URL}")

    # Mask the secret key for production logs
    masked_key = LK_KEY[:4] + '...' if LK_KEY and len(LK_KEY) > 4 else 'NOT SET or TOO SHORT'
    masked_secret = LK_SECRET[:4] + '...' if LK_SECRET and len(LK_SECRET) > 4 else 'NOT SET or TOO SHORT'

    logger.info(f"LIVEKIT_API_KEY: {masked_key}")
    logger.info(f"LIVEKIT_API_SECRET: {masked_secret}")
    logger.info("---------------------------------------")

    ########### END ############
    logger.info(f"/join-room called with room={request.room_name}, AGENT_NAME={AGENT_NAME}, lkapi_is_none={app.state.lkapi is None}")
    
    # If an agent that looks like ours is already in the room, don't dispatch again
    try:
        resp = await app.state.lkapi.room.list_participants(api.ListParticipantsRequest(room=request.room_name))
        existing = False
        for p in resp.participants:
            nm = (getattr(p, "name", "") or "").lower()
            ident = (getattr(p, "identity", "") or "").lower()
            if nm == AGENT_NAME.lower() or ident.startswith("agent") or ident == AGENT_NAME.lower():
                existing = True
                ready_identity = getattr(p, "identity", None) or getattr(p, "name", None)
                break
        if existing:
            return {
                "status": "ok",
                "message": "agent already present",
                "room": request.room_name,
                "agent": AGENT_NAME,
                "agent_identity": ready_identity,
                "dispatch_id": None,
            }
    except Exception as e:
        logger.warning(f"idempotency check failed: {e}")
    
    
    
    if app.state.lkapi is None:
        raise HTTPException(
            status_code=503,
            detail=("LiveKit API client not initialized. "
                    "Set SKIP_LK_API_INIT=0 and configure LIVEKIT_URL/KEY/SECRET.")
        )
        

    # 1) Create the explicit dispatch for this room/agent
    #if app.state.lkapi is None:
    # We’re inside an async request handler -> loop is running.
        #app.state.lkapi = api.LiveKitAPI(url=LK_URL, api_key=LK_KEY, api_secret=LK_SECRET)
    
    
    # ensure room exists and stays alive a bit
    try:
        await app.state.lkapi.room.create_room(
            api.CreateRoomRequest(
                name=request.room_name,
                empty_timeout=300,     # keep room for 5 minutes after it’s empty
                # max_participants=10, # optional
            )
        )
        logger.info(f"Room '{request.room_name}' created (or already existed).")
    except Exception as e:
        logger.info(f"create_room skipped/failed (likely exists): {e}")
    
    logger.info(f"create dispatch request for agent {AGENT_NAME}")
    try:
        dispatch = await app.state.lkapi.agent_dispatch.create_dispatch(
            api.CreateAgentDispatchRequest(
                agent_name=AGENT_NAME,
                room=request.room_name,
            )
        )
        logger.info(f"Dispatch created: id={dispatch.id} room={request.room_name} agent={AGENT_NAME}")
    except api.TwirpError as e:
        raise HTTPException(status_code=502, detail=f"LiveKit dispatch error: {e.message}")

    # 2) Block until the agent is visible in the room (readiness probe)
    #    NOTE: adjust timeout if your first-run needs extra seconds (e.g., model downloads).
    ready_identity = await _wait_for_agent_in_room(
        room_name=request.room_name,
        agent_name=AGENT_NAME,
        timeout_s=90,
    )

    if not ready_identity:
        # Optional: clean up the dispatch so repeated clicks don't pile up
        with contextlib.suppress(Exception):
            await app.state.lkapi.agent_dispatch.delete_dispatch(dispatch.id, request.room_name)

        raise HTTPException(
            status_code=504,
            detail=f"Timed out waiting for agent '{AGENT_NAME}' to join room '{request.room_name}'."
        )

    # 3) Return success only when the agent is actually present
    return {
        "status": "ok",
        "message": "agent ready",
        "room": request.room_name,
        "agent": AGENT_NAME,
        "agent_identity": ready_identity,
        "dispatch_id": dispatch.id,
    }



"""
@app.post("/join-room")
async def join_room_endpoint(request: JoinRoomRequest):
    logger.info(f"/join-room called with room={request.room_name}, AGENT_NAME={AGENT_NAME}, lkapi_is_none={app.state.lkapi is None}")
    if app.state.lkapi is None:
        raise HTTPException(
            status_code=503,
            detail=("LiveKit API client not initialized. "
                    "Set SKIP_LK_API_INIT=0 and configure LIVEKIT_URL/KEY/SECRET.")
        )
    try:
        dispatch = await app.state.lkapi.agent_dispatch.create_dispatch(
            api.CreateAgentDispatchRequest(
                agent_name=AGENT_NAME,
                room=request.room_name,
            )
        )
        return {
            "status": "ok",
            "message": "dispatch created",
            "room": request.room_name,
            "agent": AGENT_NAME,
            "dispatch_id": dispatch.id,
        }
    except api.TwirpError as e:
        raise HTTPException(status_code=502, detail=f"LiveKit dispatch error: {e.message}")
"""
#Added debug for room details (participants)
@app.get("/debug/participants/{room_name}")
async def debug_participants(room_name: str):
    resp = await app.state.lkapi.room.list_participants(api.ListParticipantsRequest(room=room_name))
    return {
        "count": len(resp.participants),
        "participants": [
            {"identity": getattr(p, "identity", None),
             "name": getattr(p, "name", None),
             "metadata": getattr(p, "metadata", None)}
            for p in resp.participants
        ],
    }

### END




def handle_exception(exc_type, exc_value, exc_traceback):
    """Handle uncaught exceptions."""
    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

sys.excepthook = handle_exception
