import asyncio
import logging
import os
import json
from dotenv import load_dotenv
load_dotenv(".env.local")
from livekit import agents, rtc
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import google, silero


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# -------------------------------------------------
# Malayalam Voice Agent
# -------------------------------------------------
class MalayalamVoiceAgent(Agent):
    def __init__(self):
        chatbot_instructions = """
You are an expert AI voice agent representing Exponential Digital Solutions (10xDS).

Your responsibilities:
- Answer user questions accurately and professionally
- Promote Exponential Digital Solutions' AI voice agent solutions
- Use only information from the provided knowledge base

If answer is not available:
"I'm sorry, I don't have that information right now. For further assistance, you can contact our team at connect@10xds.com or call us at +14782538584."

For questions unrelated to Exponential Digital Solutions or AI voice agents:
"I can only help with questions related to Exponential Digital Solutions and our AI voice agent solutions."

---

Communication style:
- Professional, confident, and helpful
- Avoid exaggerations or unsubstantiated claims
- Use clear and concise language
- When listing features or plans, present them as points or short paragraphs
- Emphasize Exponential Digital Solutions' key advantages:
  - Automation
  - Multilingual support
  - Voice cloning
  - Integration capabilities
  - Security and compliance

---

Context understanding:
- When asked about industries → Explain relevant use cases
- When asked about pricing → Summarize available plans without giving exact numbers
- When asked about features → Describe key benefits and differentiators of AI voice agents
- When asked for demo or consultation → Suggest scheduling by contacting Exponential Digital Solutions via connect@10xds.com or call us at +14782538584

---

Response approach:
- Maintain accuracy and consistency with the knowledge base
- Provide structured and easy-to-understand answers
- Keep a conversational yet professional tone
- When writing point headings, do not use asterisks (*) for highlighting. Use a colon (:) after the heading

---

CRITICAL - Language and TTS Instructions:
- Regardless of whether the user speaks in Malayalam or English, provide ALL your responses in MALAYALAM language only
- Write your responses using Malayalam script (മലയാളം)
- Speak natural Malayalam while maintaining professionalism
- Technical terms can be kept in English if necessary (e.g., AI Voice Agent, automation) but integrate them naturally into Malayalam sentences
- Your responses will be converted to speech by a Malayalam TTS system, so:
  - Write complete Malayalam sentences with proper grammar
  - Use natural Malayalam expressions and idioms where appropriate
  - Avoid complex English phrases that don't translate well
  - Keep sentence structure simple and clear for natural speech flow
  - Use conversational Malayalam that sounds natural when spoken aloud
        """

        super().__init__(
            instructions=chatbot_instructions,
            stt=google.STT(
                languages="ml-IN",
                interim_results=True,
                punctuate=False,  
                enable_voice_activity_events=True,
                model="chirp_2",  
                location="us-central1",  
                use_streaming=True,
            ),
            llm=google.LLM(model="gemini-2.5-flash"),  
            tts=google.TTS(
                credentials_file=os.getenv("GOOGLE_APPLICATION_CREDENTIALS"),
                use_streaming=True,
                language="ml-IN",
                voice_name="ml-IN-Chirp3-HD-Achernar",
                speaking_rate=1.0,
            ),
            vad=silero.VAD.load()
        )

    async def on_enter(self):
        greeting = (
            "നമസ്കാരം! Exponential Digital Solutions-ലേക്ക് സ്വാഗതം. ഞാൻ നിങ്ങളുടെ AI വോയ്‌സ് അസിസ്റ്റന്റാണ്. നിങ്ങളെ എങ്ങനെ സഹായിക്കാം?"
        )
        await self.session.say(greeting)


# -------------------------------------------------
# Cache streaming fragments
# -------------------------------------------------
full_text_cache = ""


async def on_conversation_item_delta(session: AgentSession, ev):
    """Fires while the LLM is streaming. Cache fragments progressively and stream them."""
    global full_text_cache
    try:
        if getattr(ev.item, "role", None) == "assistant":
            fragment = getattr(ev.item, "delta_text", None)
            if fragment:
                full_text_cache += fragment

                # Stream fragment to frontend in real-time
                fragment_payload = {
                    "type": "stream_agent_fragment",
                    "text": full_text_cache,
                    "interrupted": False
                }
                # use ctx.room equivalent at publish time — here we use session.room if available
                try:
                    # session.room should be set after session.start, but publishing via session.room is safe here
                    if getattr(session, "room", None):
                        await session.room.local_participant.publish_data(
                            json.dumps(fragment_payload).encode(),
                            topic="agent_text"
                        )
                    else:
                        # As a fallback, try publishing to a room passed via ev or elsewhere (rare)
                        logger.debug("session.room not available when publishing delta fragment")
                except Exception as e:
                    logger.exception("Error publishing delta fragment: %s", e)
    except Exception as e:
        logger.exception("Error caching or streaming delta: %s", e)


# -------------------------------------------------
# When full LLM message is finalized
# -------------------------------------------------
async def on_conversation_item_added(session: AgentSession, ev, room):
    """Triggered when a complete assistant turn is committed."""
    global full_text_cache
    try:
        if getattr(ev.item, "role", None) != "assistant":
            return

        full_text = getattr(ev.item, "text_content", None) or getattr(ev.item, "text", None)
        if not full_text:
            logger.warning("No text content found in committed message")
            return

        # Log and publish full committed message
        logger.info(f"🟢 Full agent text committed (first 100 chars): {full_text[:100]}...")
        logger.debug(f"\n=== FULL AGENT RESPONSE (COMMITTED) ===\n{full_text}\n========================================\n")

        payload = {
            "type": "full_agent_transcript",
            "text": full_text,
            "interrupted": False
        }
        await room.local_participant.publish_data(
            json.dumps(payload).encode(),
            topic="agent_text"
        )
        logger.info("✅ Full agent message published to frontend (committed)")

        # Clear cache for next turn
        full_text_cache = ""

    except Exception as e:
        logger.exception("Error in on_conversation_item_added: %s", e)


# -------------------------------------------------
# Handle playback interruption
# -------------------------------------------------
async def on_playback_finished(session: AgentSession, ev):
    """
    Triggered when the TTS finishes or is interrupted mid-playback.
    On interrupt: Stop speech immediately but let LLM finish silently.
    """
    global full_text_cache
    try:
        interrupted = getattr(ev, "interrupted", False)
        logger.info(f"🔊 Playback finished (interrupted={interrupted})")

        if interrupted:
            logger.info("🟡 User interrupted — stopping TTS, keeping LLM active.")
            # We do NOT call session.aclose() here!
            # This ensures LLM continues generating until its full response is done.
            # Once that happens, `conversation_item_added` will fire automatically.
            
            # Optionally: publish the current partial text to the frontend
            if full_text_cache:
                partial_payload = {
                    "type": "partial_agent_transcript",
                    "text": full_text_cache,
                    "interrupted": True
                }
                try:
                    if getattr(session, "room", None):
                        await session.room.local_participant.publish_data(
                            json.dumps(partial_payload).encode(),
                            topic="agent_text"
                        )
                    else:
                        logger.debug("session.room not available when publishing partial payload")
                except Exception as e:
                    logger.exception("Error publishing partial payload: %s", e)
                logger.info("🟣 Partial transcript sent to frontend during interruption")

    except Exception as e:
        logger.exception("Error in playback_finished handler: %s", e)


# -------------------------------------------------
# Entrypoint
# -------------------------------------------------
async def entrypoint(ctx: JobContext):
    logger.info("🚀 Malayalam Agent entrypoint called")

    session = AgentSession()

    # Capture fragments as they stream
    session.on("conversation_item_delta", lambda ev: asyncio.create_task(on_conversation_item_delta(session, ev)))
    
    # Handle user transcription events and publish to frontend via data channel
    async def on_user_transcribed(ev):
        """Publish user partial/final transcripts to frontend."""
        try:
            if hasattr(ev, 'transcript') and ev.transcript:
                is_final = getattr(ev, 'final', False)
                payload = {
                    "type": "user_text",
                    "text": ev.transcript,
                    "final": is_final
                }
                await ctx.room.local_participant.publish_data(
                    json.dumps(payload).encode(),
                    topic="user_text"
                )
                logger.info(f"📤 Published user transcript: '{ev.transcript[:50]}...' (final: {is_final})")
        except Exception as e:
            logger.exception("Error publishing user transcript: %s", e)

    # Attach to user input events (Deepgram/LiveKit fires these)
    session.on("user_input_transcribed", lambda ev: asyncio.create_task(on_user_transcribed(ev)))
    # Fallback for partials if separate event
    session.on("stt_partial", lambda ev: asyncio.create_task(on_user_transcribed(ev)))  # Adjust event name if needed

    # Handle full committed items
    session.on("conversation_item_added", lambda ev: asyncio.create_task(on_conversation_item_added(session, ev, ctx.room)))

    # Handle playback interruptions
    try:
        session.output.audio.on("playback_finished", lambda ev: asyncio.create_task(on_playback_finished(session, ev)))
        logger.info("🎧 Playback handler attached successfully")
    except Exception as e:
        logger.exception("Error attaching playback handler: %s", e)

    # ----------------------------------------------------------------
    # Control data handler (force STT flush) and auto-flush monitor
    # ----------------------------------------------------------------
    async def on_control_data(payload: bytes, participant):
        """Handle custom control signals like force_stt_flush from frontend."""
        try:
            # payload may be a bytes-like or have .data depending on caller — defensive decode
            if isinstance(payload, dict) and "data" in payload:
                raw = payload["data"]
            else:
                raw = payload
            msg = json.loads(raw.decode())
        except Exception as e:
            logger.debug("Invalid control payload received: %s", e)
            return

        if not isinstance(msg, dict):
            return

        if msg.get("type") == "force_stt_flush":
            logger.info("🟠 Force STT flush requested (mic muted)")
            try:
                if hasattr(session, "input") and hasattr(session.input, "flush"):
                    await session.input.flush()
                    logger.info("✅ STT stream flushed successfully on user mute.")
                else:
                    logger.warning("session.input.flush() not available on this SDK version.")
            except Exception as e:
                logger.exception("⚠️ Could not flush STT stream: %s", e)

    # attach control-data listener to the room
    try:
        ctx.room.on("data_received", lambda payload, participant: asyncio.create_task(on_control_data(payload, participant)))
        logger.info("🔌 Control data handler attached (listening for force_stt_flush)")
    except Exception as e:
        logger.exception("Error attaching control data handler: %s", e)

    # Optional: user input lifecycle logs for debugging
    try:
        session.on("user_input_started", lambda ev: logger.info("🎙️ User speech detected (started)"))
        session.on("user_input_transcribed", lambda ev: logger.info("🧾 User input finalized (transcribed)"))
    except Exception:
        # Not fatal — some SDK versions or setups may not fire these events
        pass

    # Auto-flush monitor: flush STT after short idle periods to avoid transcripts hanging when user mutes quickly.
    async def monitor_stt_auto_flush():
        """Automatically flush STT stream if silence persists."""
        last_flush = 0.0
        MIN_FLUSH_INTERVAL = 1.0  # seconds between forced flush attempts
        while True:
            await asyncio.sleep(0.75)
            try:
                now = asyncio.get_event_loop().time()
                if (now - last_flush) < MIN_FLUSH_INTERVAL:
                    continue

                # Only attempt flush when output audio is not playing (i.e. agent not speaking)
                # and when session.input.flush() is available.
                if getattr(session, "output", None) and getattr(session.output, "audio", None):
                    is_playing = getattr(session.output.audio, "is_playing", False)
                else:
                    is_playing = False

                if (not is_playing) and hasattr(session, "input") and hasattr(session.input, "flush"):
                    try:
                        await session.input.flush()
                        last_flush = now
                        logger.debug("🕐 Auto-flushed STT (periodic check).")
                    except Exception as e:
                        logger.debug("Auto-flush attempt failed: %s", e)
            except Exception as e:
                logger.debug("monitor_stt_auto_flush loop error: %s", e)

    # start monitor task
    asyncio.create_task(monitor_stt_auto_flush())

    # Start the voice agent
    await session.start(agent=MalayalamVoiceAgent(), room=ctx.room)
    logger.info("🤖 Malayalam Voice Agent is ready and listening.")


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