import asyncio
import json
import logging
from typing import Optional, List
from datetime import datetime
from pathlib import Path
import sys

import asyncpg
from dotenv import load_dotenv

from livekit import agents
from livekit.agents import (
    JobContext,
    AutoSubscribe,
    WorkerOptions,
    llm,
    voice,
    function_tool,
)
from livekit.agents.voice import room_io
from livekit.plugins import openai, noise_cancellation, silero

# Local imports
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from config.settings import settings
from config.database import db_manager
from app.services.customer_service import CustomerService
from app.services.queue_manager import QueueManager
from app.services.transcript_service import TranscriptService
from app.services.sentiment_analyzer import SentimentAnalyzer
from app.tools.account_tools import AccountTools
from app.tools.scheduling_tools import SchedulingTools
from app.tools.knowledge_base import KnowledgeBase
from app.agents import prompts

load_dotenv()

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)


class OpenAICustomerServiceAgent:
    """
    OpenAI-based customer service voice agent for LiveKit SIP calls.
    Handles both inbound phone calls and softphone (MicroSIP) calls.
    
    This version uses separate models for STT, TTS, and LLM instead of 
    RealtimeModel for all three, which avoids compatibility issues.
    """

    def __init__(self) -> None:
        # Database services
        self.db_pool: Optional[asyncpg.Pool] = None
        self.customer_service: Optional[CustomerService] = None
        self.queue_manager: Optional[QueueManager] = None
        self.transcript_service: Optional[TranscriptService] = None
        self.sentiment_analyzer: Optional[SentimentAnalyzer] = None

        # Function tools
        self.account_tools: Optional[AccountTools] = None
        self.scheduling_tools: Optional[SchedulingTools] = None
        self.knowledge_base: Optional[KnowledgeBase] = None

        # Call state (per job / per call)
        self.session_id: Optional[int] = None
        self.customer_id: Optional[int] = None
        self.queue_id: Optional[int] = None
        self.phone_number: Optional[str] = None
        self.call_type: Optional[str] = None
        self.customer_name: Optional[str] = None
        self.transfer_requested: bool = False
        self.is_first_time_customer: bool = False

        logger.info("OpenAICustomerServiceAgent initialized")

    # ======================================================================
    # DATABASE INITIALIZATION
    # ======================================================================

    async def initialize_database(self) -> None:
        """
        Initialize database connection pool and all dependent services.
        """
        try:
            await db_manager.connect()
            self.db_pool = db_manager.pool

            self.customer_service = CustomerService(self.db_pool)
            self.queue_manager = QueueManager(self.db_pool)
            self.transcript_service = TranscriptService(self.db_pool)
            self.sentiment_analyzer = SentimentAnalyzer(self.db_pool)

            self.account_tools = AccountTools(self.db_pool)
            self.scheduling_tools = SchedulingTools(self.db_pool)
            self.knowledge_base = KnowledgeBase(self.db_pool)

            logger.info("Database and services initialized successfully")
        except Exception as e:
            logger.error("Failed to initialize database: %s", e, exc_info=True)
            raise

    # ======================================================================
    # CUSTOMER CONTEXT
    # ======================================================================

    async def get_customer_context(self, phone_number: str) -> str:
        """
        Build comprehensive customer context for the AI.

        Args:
            phone_number: Customer phone number.

        Returns:
            Formatted customer context string.
        """
        try:
            logger.info("Fetching customer context for %s", phone_number)

            customer = await self.customer_service.get_customer_info(phone_number)

            if not customer:
                self.is_first_time_customer = True
                logger.info("New customer: %s", phone_number)
                return (
                    f"New customer calling from {phone_number}. "
                    f"This is their first interaction with our service."
                )

            # Returning customer
            self.customer_id = customer["customer_id"]
            self.customer_name = customer.get("name")
            self.is_first_time_customer = False

            total_calls = customer.get("total_calls", 0)
            logger.info(
                "Returning customer: %s (ID: %s, %s previous calls)",
                self.customer_name,
                self.customer_id,
                total_calls,
            )

            history = await self.customer_service.get_call_history(
                customer["customer_id"], limit=3
            )

            context = f"""Customer Information:
- Name: {customer.get("name", "Unknown")}
- Phone: {phone_number}
- Customer ID: {customer["customer_id"]}
- Member since: {customer.get("created_at", "Unknown")}
- Total previous calls: {total_calls}
- Last call: {customer.get("last_call_time", "Never")}
"""

            if history:
                context += "\nRecent Call History:\n"
                for idx, call in enumerate(history, 1):
                    summary = call.get("summary", "No summary")
                    duration = call.get("duration_seconds", 0)
                    sentiment = call.get("sentiment", "neutral")
                    context += (
                        f"{idx}. {call['start_time']} "
                        f"({duration}s, {sentiment}): {summary}\n"
                    )

            return context

        except Exception as e:
            logger.error("Error getting customer context: %s", e, exc_info=True)
            return f"Customer calling from {phone_number} (context unavailable)"

    # ======================================================================
    # FUNCTION TOOLS
    # ======================================================================

    def build_tools(self) -> List[llm.FunctionTool]:
        """
        Build function tools for the agent.

        Returns:
            List of FunctionTool objects.
        """
        tools: List[llm.FunctionTool] = []

        async def transfer_to_human(reason: str) -> str:
            """
            Transfer call to a human agent.
            The actual bridging to a human should be handled by your
            application or routing layer; here we only mark state and
            generate a response to the caller.
            """
            self.transfer_requested = True
            logger.info("Transfer requested: %s", reason)
            return prompts.get_transfer_message(reason)

        tools.append(
            function_tool(
                transfer_to_human,
                name="transfer_to_human",
                description=(
                    "Transfer the call to a human agent. Use when the customer requests "
                    "a human, is frustrated, or the issue requires human judgment."
                ),
            )
        )

        logger.info("Built %d function tools", len(tools))
        return tools

    # ======================================================================
    # EVENT HANDLERS (TRANSCRIPTS AND SENTIMENT)
    # ======================================================================

    def setup_event_handlers(self, session: voice.AgentSession) -> None:
        """
        Attach handlers for transcripts and sentiment analysis.

        Args:
            session: AgentSession instance.
        """

        async def handle_user_speech(msg: llm.ChatMessage) -> None:
            """
            Handle user speech: log, store transcript, analyze sentiment.
            """
            try:
                text = getattr(msg, "content", None) or getattr(msg, "text", None)
                if not text:
                    return

                logger.info("User: %s", text)

                # Save transcript to DB
                if self.transcript_service and self.session_id:
                    await self.transcript_service.save_transcript(
                        self.session_id,
                        "customer",
                        text,
                        confidence=0.95,
                    )

                # Analyze sentiment based on recent conversation window
                if self.sentiment_analyzer and self.session_id:
                    sentiment = await self.sentiment_analyzer.analyze_conversation(
                        self.session_id,
                        window_size=3,
                    )

                    if sentiment:
                        polarity = sentiment.get("polarity", 0.0)
                        label = sentiment.get("label", "neutral")
                        logger.info(
                            "Sentiment: %s (polarity: %.2f)", label, polarity
                        )

                        if sentiment.get("recommend_transfer"):
                            logger.warning(
                                "Negative sentiment detected in session %s",
                                self.session_id,
                            )

                        if sentiment.get("strong_negative"):
                            logger.error(
                                "Strong negative sentiment detected in session %s",
                                self.session_id,
                            )

            except Exception as e:
                logger.error("Error handling user speech: %s", e, exc_info=True)

        @session.on("user_speech_committed")
        def _on_user_speech(msg: llm.ChatMessage) -> None:
            asyncio.create_task(handle_user_speech(msg))

        async def handle_agent_speech(msg: llm.ChatMessage) -> None:
            """
            Handle agent speech: log and store transcript.
            This will include the greeting and all subsequent replies.
            """
            try:
                text = getattr(msg, "content", None) or getattr(msg, "text", None)
                if not text:
                    return

                logger.info("Agent: %s", text)

                if self.transcript_service and self.session_id:
                    await self.transcript_service.save_transcript(
                        self.session_id,
                        "ai_agent",
                        text,
                        confidence=1.0,
                    )
            except Exception as e:
                logger.error("Error handling agent speech: %s", e, exc_info=True)

        @session.on("agent_speech_committed")
        def _on_agent_speech(msg: llm.ChatMessage) -> None:
            asyncio.create_task(handle_agent_speech(msg))

        async def handle_function_calls(calls) -> None:
            """
            Handle function calls: log usage and store in transcripts.
            """
            try:
                for call in calls:
                    function_name = getattr(call, "function_name", "unknown")
                    logger.info("Function executed: %s", function_name)

                    if self.transcript_service and self.session_id:
                        await self.transcript_service.save_transcript(
                            self.session_id,
                            "system",
                            f"Function called: {function_name}",
                            confidence=1.0,
                        )

                    if function_name == "transfer_to_human" and self.transfer_requested:
                        logger.info("Transfer to human agent flagged in state")

            except Exception as e:
                logger.error("Error handling function calls: %s", e, exc_info=True)

        @session.on("function_calls_finished")
        def _on_function_calls(calls) -> None:
            asyncio.create_task(handle_function_calls(calls))

        logger.info("Event handlers configured")

    # ======================================================================
    # MAIN ENTRYPOINT (PER CALL)
    # ======================================================================

    async def entrypoint(self, ctx: JobContext) -> None:
        """
        Main agent entrypoint; called by LiveKit for each job / call.

        This handles one complete call lifecycle:
        - connect to room
        - build context and session
        - greet caller
        - run conversation
        - cleanup and persist metadata
        """
        try:
            # Initialize DB and services
            await self.initialize_database()

            # Connect to room
            await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
            logger.info("Connected to room: %s", ctx.room.name)

            # Check if another agent already exists in this room
            existing_agents = [
                p for p in ctx.room.remote_participants.values()
                if p.identity.startswith("agent-")
            ]
            
            if len(existing_agents) > 0:
                logger.warning(
                    "Another agent already exists in room %s (found %d agents). "
                    "Exiting to prevent duplicate agents.",
                    ctx.room.name,
                    len(existing_agents)
                )
                # Mark queue as completed since another agent is handling
                if self.queue_manager and ctx.job.metadata:
                    try:
                        metadata = json.loads(ctx.job.metadata)
                        queue_id = metadata.get("queue_id")
                        if queue_id:
                            await self.queue_manager.mark_completed(queue_id)
                    except:
                        pass
                return

            # Parse job metadata from SIP dispatch
            raw_metadata = ctx.job.metadata or "{}"
            logger.info("Job metadata raw: %s", raw_metadata)

            try:
                metadata = json.loads(raw_metadata)
            except json.JSONDecodeError:
                logger.warning("Job metadata is not valid JSON: %s", raw_metadata)
                metadata = {}

            # From your dispatch rule:
            # "metadata": "{\"source_number\": \"+15183171307\", \"service\": \"customer_service\"}"
            self.phone_number = (
                metadata.get("phone_number")
                or metadata.get("source_number")
                or metadata.get("from_number")
                or metadata.get("from")
                or "unknown"
            )

            # Default to inbound; override if provided
            self.call_type = metadata.get(
                "call_type",
                prompts.CallType.INBOUND,
            )

            logger.info(
                "Processing %s call from %s", self.call_type, self.phone_number
            )

            # Build customer context
            customer_context = await self.get_customer_context(self.phone_number)

            # Ensure customer record exists
            if not self.customer_id and self.customer_service:
                logger.info(
                    "Creating customer record for phone number %s", self.phone_number
                )
                customer = await self.customer_service.get_or_create_customer(
                    self.phone_number,
                    name=(
                        f"Customer-{self.phone_number[-4:]}"
                        if self.phone_number != "unknown"
                        else "Customer-unknown"
                    ),
                )
                self.customer_id = customer["customer_id"]
                logger.info("Customer ID: %s", self.customer_id)

            # Create call session in DB
            if self.customer_service and self.customer_id:
                self.session_id = await self.customer_service.create_session(
                    self.customer_id,
                    ctx.room.name,
                )
                logger.info("Session ID: %s", self.session_id)

            # Add to queue for inbound calls
            if self.call_type == prompts.CallType.INBOUND and self.queue_manager:
                self.queue_id = await self.queue_manager.add_to_queue(
                    self.customer_id,
                    self.phone_number,
                    ctx.room.name,
                    priority=1 if self.is_first_time_customer else 2,
                )
                logger.info("Queue ID: %s", self.queue_id)

            # ==================================================================
            # CREATE SEPARATE MODELS FOR STT, TTS, AND LLM
            # ==================================================================

            system_instructions = prompts.get_system_instructions(
                customer_context,
                self.call_type,
                self.is_first_time_customer,
            )

            # Create separate models instead of using RealtimeModel for all three
            # This avoids the RealtimeCapabilities.streaming attribute error
            
            # LLM: GPT-4 or GPT-4o for conversation
            # IMPORTANT: Use a CHAT model, not a realtime model
            # Chat models: gpt-4o, gpt-4-turbo, gpt-4, gpt-3.5-turbo
            # Do NOT use: gpt-4o-realtime-preview (that's for RealtimeModel only)
            llm_model = openai.LLM(
                model="gpt-4o",  # Use standard chat model
                temperature=settings.openai_temperature,
            )
            logger.info("OpenAI LLM created: gpt-4o")

            # TTS: OpenAI TTS for speech synthesis
            tts_model = openai.TTS(
                voice=settings.openai_voice,  # e.g., "alloy", "echo", "fable", "onyx", "nova", "shimmer"
                model="tts-1",  # or "tts-1-hd" for higher quality
            )
            logger.info("OpenAI TTS created with voice: %s", settings.openai_voice)

            # STT: OpenAI Whisper for speech recognition
            stt_model = openai.STT(
                model="whisper-1",
                language="en",  # Set language for better accuracy
            )
            logger.info("OpenAI STT (Whisper) created")

            tools = self.build_tools()

            # Create AgentSession with separate models
            session = voice.AgentSession(
                llm=llm_model,
                tts=tts_model,
                stt=stt_model,
            )
            logger.info("AgentSession created with separate STT, TTS, and LLM models")

            # Create Agent with instructions, tools, and VAD
            # VAD is required when using non-streaming STT like Whisper
            agent = voice.Agent(
                instructions=system_instructions,
                llm=llm_model,
                tools=tools,
                vad=silero.VAD.load(),  # Add VAD for streaming support with Whisper
            )
            logger.info("Voice Agent created with tools and Silero VAD")

            # Attach transcript and function handlers
            self.setup_event_handlers(session)

            # Krisp-based noise cancellation for telephony
            # This requires: pip install "livekit-plugins-noise-cancellation~=0.2"
            noise_filter = noise_cancellation.BVCTelephony()

            # Start the session
            await session.start(
                agent=agent,
                room=ctx.room,
                room_options=room_io.RoomOptions(
                    audio_input=room_io.AudioInputOptions(
                        noise_cancellation=noise_filter,
                    ),
                ),
            )
            logger.info(
                "Agent session started successfully with Krisp BVCTelephony noise cancellation"
            )

            # Wait for a participant (phone or MicroSIP) to join
            # Filter out other agents to avoid infinite loops
            logger.info("Waiting for participants to join room %s", ctx.room.name)
            
            timeout_seconds = 10
            start_time = asyncio.get_event_loop().time()
            
            while True:
                # Filter out agent participants - only count real SIP/phone participants
                real_participants = [
                    p for p in ctx.room.remote_participants.values()
                    if not p.identity.startswith("agent-")
                ]
                
                logger.info(
                    "Current participants: %d total, %d real (non-agent)",
                    len(ctx.room.remote_participants),
                    len(real_participants)
                )
                
                if len(real_participants) > 0:
                    break
                    
                if asyncio.get_event_loop().time() - start_time > timeout_seconds:
                    logger.error(
                        "Timeout: No real participant joined within %d seconds",
                        timeout_seconds,
                    )
                    return
                    
                await asyncio.sleep(0.1)

            logger.info(
                "Real participant joined; count: %d",
                len(real_participants),
            )
            for participant in real_participants:
                logger.info("Real participant: %s", participant.identity)

            # ==================================================================
            # GREETING: agent speaks first, clearly
            # ==================================================================

            greeting = prompts.get_greeting(
                self.call_type,
                self.is_first_time_customer,
                self.customer_name,
            )

            if greeting:
                logger.info("Sending greeting: %s", greeting)
                # Allow interruptions so user can speak over greeting if needed
                await session.say(greeting, allow_interruptions=True)

            # Keep session alive until all real (non-agent) participants disconnect
            logger.info("Keeping session alive until participant disconnects.")
            while True:
                real_participants = [
                    p for p in ctx.room.remote_participants.values()
                    if not p.identity.startswith("agent-")
                ]
                if len(real_participants) == 0:
                    break
                await asyncio.sleep(0.5)

            logger.info("Participant disconnected, conversation completed")

            # ==================================================================
            # CLEANUP
            # ==================================================================

            try:
                if self.session_id and self.customer_service:
                    await self.customer_service.update_session_end(
                        self.session_id,
                        json.dumps(
                            {
                                "transfer_requested": self.transfer_requested,
                                "completed_at": datetime.now().isoformat(),
                                "first_time_customer": self.is_first_time_customer,
                                "call_type": self.call_type,
                            }
                        ),
                    )

                if self.queue_id and self.queue_manager:
                    await self.queue_manager.mark_completed(self.queue_id)

                logger.info(
                    "Session %s completed (%s)",
                    self.session_id,
                    "transferred" if self.transfer_requested else "resolved by AI",
                )

            except Exception as cleanup_err:
                logger.error(
                    "Error during cleanup: %s", cleanup_err, exc_info=True
                )

        except Exception as e:
            logger.error("Error in agent entrypoint: %s", e, exc_info=True)

            # Best-effort cleanup on error
            try:
                if self.queue_id and self.queue_manager:
                    await self.queue_manager.mark_abandoned(self.queue_id)

                if self.session_id and self.customer_service:
                    await self.customer_service.update_session_end(
                        self.session_id,
                        json.dumps(
                            {
                                "transfer_requested": self.transfer_requested,
                                "completed_at": datetime.now().isoformat(),
                                "first_time_customer": self.is_first_time_customer,
                                "call_type": self.call_type,
                                "error": str(e),
                            }
                        ),
                    )
            except Exception as inner:
                logger.error(
                    "Error during error cleanup: %s", inner, exc_info=True
                )


# ======================================================================
# MODULE-LEVEL ENTRYPOINT FOR LIVEKIT WORKER
# ======================================================================


async def entrypoint(ctx: JobContext) -> None:
    """
    LiveKit worker entrypoint.
    A fresh agent instance is created per job (per call),
    so state is not shared across calls.
    """
    agent = OpenAICustomerServiceAgent()
    await agent.entrypoint(ctx)


if __name__ == "__main__":
    agents.cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            agent_name="AgnoX-AI-Agent",
        )
    )