#
# Copyright (c) 2025, Daily
#
# SPDX-License-Identifier: BSD 2-Clause License
#

import os
import sys

from dotenv import load_dotenv
from loguru import logger
from pipecat.adapters.schemas.function_schema import FunctionSchema
from pipecat.adapters.schemas.tools_schema import ToolsSchema
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.runner import PipelineRunner
from pipecat.pipeline.task import PipelineParams, PipelineTask
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import (
    LLMContextAggregatorPair,
    LLMUserAggregatorParams,
)
from pipecat.runner.types import RunnerArguments
from pipecat.runner.utils import parse_telephony_websocket
from pipecat.serializers.twilio import TwilioFrameSerializer
from pipecat.services.cartesia.tts import CartesiaTTSService
from pipecat.services.deepgram.stt import DeepgramSTTService
from pipecat.services.google.llm import GoogleLLMService
from pipecat.transports.base_transport import BaseTransport
from pipecat.transports.websocket.fastapi import (
    FastAPIWebsocketParams,
    FastAPIWebsocketTransport,
)

from dependencies import (
    build_app_resources,
    build_book_appointment_tool,
    build_enrich_call_context,
    build_get_service_availability_tool,
    build_get_service_tool,
)
from prompt.outbound_receptionist import SYSTEM_INSTRUCTION

load_dotenv(override=True)

logger.remove(0)
logger.add(sys.stderr, level="DEBUG")


async def run_bot(
    transport: BaseTransport,
    handle_sigint: bool,
    access_token: str | None = None,
    to_number: str | None = None,
):
    get_service_tool = build_get_service_tool()
    get_service_availability_tool = build_get_service_availability_tool()
    book_appointment_tool = build_book_appointment_tool()
    enrich_context = build_enrich_call_context()

    app_resources = await enrich_context.execute(
        build_app_resources(access_token=access_token),
        to_number,
    )

    get_service_schema = FunctionSchema(
        name="get_service",
        description="Fetch services that have at least one stylist assigned.",
        properties={},
        required=[],
    )
    get_service_availability_schema = FunctionSchema(
        name="get_service_availability",
        description="Fetch availability for one or more services on a given date.",
        properties={
            "serviceNames": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Service names to check availability for.",
            },
            "date": {
                "type": "string",
                "description": "Date to check in YYYY-MM-DD format.",
            },
        },
        required=["serviceNames", "date"],
    )
    book_appointment_schema = FunctionSchema(
        name="book_appointment",
        description=(
            "Book one or more services sequentially at the requested date and time. "
            "Optionally apply a promotion using offer_title when the caller names one."
        ),
        properties={
            "serviceNames": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Service names to book, in order.",
            },
            "requestedStart": {
                "type": "object",
                "properties": {
                    "date": {
                        "type": "string",
                        "description": "Appointment date in YYYY-MM-DD format.",
                    },
                    "time": {
                        "type": "string",
                        "description": "Appointment time in 24-hour HH:mm format.",
                    },
                },
                "required": ["date", "time"],
            },
            "offer_title": {
                "type": "string",
                "description": "Optional offer title to apply to the first service only.",
            },
        },
        required=["serviceNames", "requestedStart"],
    )
    tools = ToolsSchema(
        standard_tools=[
            get_service_schema,
            get_service_availability_schema,
            book_appointment_schema,
        ]
    )

    llm = GoogleLLMService(
        api_key=os.getenv("GOOGLE_API_KEY"),
        settings=GoogleLLMService.Settings(
            system_instruction=SYSTEM_INSTRUCTION,
        ),
    )
    llm.register_function("get_service", get_service_tool)
    llm.register_function("get_service_availability", get_service_availability_tool)
    llm.register_function("book_appointment", book_appointment_tool)

    stt = DeepgramSTTService(api_key=os.getenv("DEEPGRAM_API_KEY"))

    tts = CartesiaTTSService(
        api_key=os.getenv("CARTESIA_API_KEY"),
        settings=CartesiaTTSService.Settings(
            voice="71a7ad14-091c-4e8e-a314-022ece01c121",  # British Reading Lady
        ),
    )

    context = LLMContext(tools=tools)
    user_aggregator, assistant_aggregator = LLMContextAggregatorPair(
        context,
        user_params=LLMUserAggregatorParams(
            vad_analyzer=SileroVADAnalyzer(),
        ),
    )

    pipeline = Pipeline(
        [
            transport.input(),  # Websocket input from client
            stt,  # Speech-To-Text
            user_aggregator,
            llm,  # LLM
            tts,  # Text-To-Speech
            transport.output(),  # Websocket output to client
            assistant_aggregator,
        ]
    )

    task = PipelineTask(
        pipeline,
        params=PipelineParams(
            audio_in_sample_rate=8000,
            audio_out_sample_rate=8000,
            enable_metrics=True,
            enable_usage_metrics=True,
        ),
        app_resources=app_resources,
    )

    @transport.event_handler("on_client_connected")
    async def on_client_connected(transport, client):
        # Kick off the outbound conversation, waiting for the user to speak first
        logger.info("Starting outbound call conversation")

    @transport.event_handler("on_client_disconnected")
    async def on_client_disconnected(transport, client):
        logger.info("Outbound call ended")
        await task.cancel()

    runner = PipelineRunner(handle_sigint=handle_sigint)

    await runner.run(task)


async def bot(runner_args: RunnerArguments):
    """Main bot entry point compatible with Pipecat Cloud."""
    transport_type, call_data = await parse_telephony_websocket(runner_args.websocket)
    logger.info(f"Auto-detected transport: {transport_type}")

    # Access custom stream parameters passed from TwiML
    # Use the body data to personalize the conversation
    # by loading customer data based on the to_number or from_number
    body_data = call_data.get("body", {})
    to_number = body_data.get("to_number")
    from_number = body_data.get("from_number")
    access_token = body_data.get("access_token")

    logger.info(f"Call metadata - To: {to_number}, From: {from_number}")

    serializer = TwilioFrameSerializer(
        stream_sid=call_data["stream_id"],
        call_sid=call_data["call_id"],
        account_sid=os.getenv("TWILIO_ACCOUNT_SID", ""),
        auth_token=os.getenv("TWILIO_AUTH_TOKEN", ""),
    )

    transport = FastAPIWebsocketTransport(
        websocket=runner_args.websocket,
        params=FastAPIWebsocketParams(
            audio_in_enabled=True,
            audio_out_enabled=True,
            add_wav_header=False,
            serializer=serializer,
        ),
    )

    handle_sigint = runner_args.handle_sigint

    await run_bot(
        transport,
        handle_sigint,
        access_token=access_token,
        to_number=to_number,
    )
