#!/usr/bin/env python3
"""
ReceptionistAI - VAPI Client Agent Template
============================================
Creates customized voice agents for new clients based on their business info.

Usage:
    python vapi_client_template.py --create "Business Name" --type trades
    python vapi_client_template.py --list-agents
    python vapi_client_template.py --test-agent "agent_id"
"""

import os
import sys
import json
import requests
import argparse
from datetime import datetime
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent.parent))


class VAPIClientTemplate:
    """Creates and manages VAPI agents for ReceptionistAI clients."""

    def __init__(self):
        self.api_key = os.getenv("VAPI_API_KEY", "5d7f9c70-7873-4182-93f3-f68db8e3a193")
        self.base_url = "https://api.vapi.ai"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        # Voice options (ElevenLabs)
        self.voices = {
            "female_au": {"provider": "11labs", "voiceId": "pFZP5JQG7iQjIQuC4Bku", "model": "eleven_turbo_v2_5"},
            "male_au": {"provider": "11labs", "voiceId": "IKne3meq5aSn9XLyUdCD", "model": "eleven_turbo_v2_5"},
            "female_professional": {"provider": "11labs", "voiceId": "Xb7hH8MSUJpSbSDYk0k2", "model": "eleven_turbo_v2_5"}
        }

        # Industry-specific templates
        self.templates = self._load_templates()

    def _load_templates(self) -> dict:
        """Load industry-specific prompt templates."""
        return {
            "trades": {
                "greeting": "G'day! Thanks for calling {business_name}. This is {ai_name}, your AI receptionist. How can I help you today?",
                "services_prompt": "We handle all kinds of {service_type} work - from small repairs to big jobs. Would you like to book a quote or get some info?",
                "booking_prompt": "I can book you in for a quote. What suburb are you in, and what's the best time for our {role} to come have a look?",
                "system_prompt": """You are {ai_name}, an AI receptionist for {business_name}, an Australian {service_type} business.

## Your Role
- Answer calls professionally with a friendly Australian manner
- Gather job details: what work is needed, location, urgency
- Book quotes/appointments into the calendar
- Take messages when the {role} is unavailable
- Handle after-hours calls professionally

## Key Information
- Business: {business_name}
- Service Type: {service_type}
- Service Areas: {service_areas}
- Operating Hours: {operating_hours}
- Emergency Contact: {emergency_contact}

## Conversation Flow
1. Greet warmly with Australian friendliness
2. Ask what they need help with
3. For quotes: Get address, job details, preferred time
4. For emergencies: Collect details, promise callback within 30 mins
5. For general inquiries: Provide helpful info or take message

## Phrases to Use
- "No worries, I can help with that"
- "Let me book you in for a quote"
- "The {role} will give you a call back"
- "Is this urgent or can it wait a day or two?"

## Never Do
- Give specific prices (say "the {role} will quote after seeing the job")
- Promise exact appointment times without checking
- Share personal details about staff"""
            },
            "medical": {
                "greeting": "Good morning, {business_name}, this is {ai_name}. How may I assist you today?",
                "services_prompt": "We offer a range of {service_type} services. Would you like to book an appointment?",
                "booking_prompt": "I can help you schedule an appointment. Are you an existing patient or new to our practice?",
                "system_prompt": """You are {ai_name}, an AI receptionist for {business_name}, a medical/health practice.

## Your Role
- Handle appointment bookings professionally
- Verify patient details (name, DOB, Medicare if applicable)
- Triage urgency appropriately
- Maintain strict confidentiality

## Key Information
- Practice: {business_name}
- Services: {service_type}
- Hours: {operating_hours}

## Urgent Indicators (Transfer/Escalate)
- Chest pain, difficulty breathing
- Severe bleeding or injury
- Mental health crisis
- Allergic reactions

## Booking Flow
1. Confirm patient identity
2. Reason for visit (brief)
3. Preferred practitioner (if any)
4. Available times
5. Confirm details

## Compliance
- Never provide medical advice
- Always recommend emergency services for urgent issues
- Maintain AHPRA compliance"""
            },
            "legal": {
                "greeting": "Thank you for calling {business_name}. This is {ai_name}. How may I direct your call?",
                "services_prompt": "We practice in {service_type}. Would you like to schedule a consultation?",
                "booking_prompt": "I can arrange an initial consultation. May I take your name and brief details about your matter?",
                "system_prompt": """You are {ai_name}, an AI receptionist for {business_name}, a law firm.

## Your Role
- Screen incoming calls professionally
- Schedule consultations
- Take detailed messages
- Maintain strict confidentiality

## Key Information
- Firm: {business_name}
- Practice Areas: {service_type}
- Partners: {staff_names}

## Important Guidelines
- Never provide legal advice
- All matters are confidential
- Existing clients: verify identity before discussing matters
- New inquiries: gather basic details only

## Booking Flow
1. Name and contact details
2. Type of legal matter (brief)
3. How they heard about us
4. Urgency level
5. Preferred solicitor (if any)"""
            },
            "generic": {
                "greeting": "Hello, thank you for calling {business_name}. This is {ai_name}, how can I help you today?",
                "services_prompt": "We'd be happy to help you with {service_type}. What can I assist you with?",
                "booking_prompt": "I can schedule that for you. What day and time works best?",
                "system_prompt": """You are {ai_name}, an AI receptionist for {business_name}.

## Your Role
- Answer calls professionally and warmly
- Book appointments and take messages
- Provide basic information about services
- Transfer to appropriate staff when needed

## Key Information
- Business: {business_name}
- Services: {service_type}
- Hours: {operating_hours}
- Location: {location}

## Conversation Guidelines
- Be friendly and helpful
- Listen carefully to caller needs
- Confirm all details before ending call
- Offer to take a message if staff unavailable"""
            }
        }

    def _make_request(self, method: str, endpoint: str, data: dict = None) -> dict:
        """Make API request to VAPI."""
        url = f"{self.base_url}{endpoint}"
        try:
            if method == "GET":
                response = requests.get(url, headers=self.headers, timeout=30)
            elif method == "POST":
                response = requests.post(url, headers=self.headers, json=data, timeout=30)
            elif method == "DELETE":
                response = requests.delete(url, headers=self.headers, timeout=30)
            else:
                return {"error": f"Unsupported method: {method}"}

            if response.status_code in [200, 201]:
                return response.json() if response.text else {"status": "success"}
            else:
                return {"error": response.text, "status_code": response.status_code}
        except Exception as e:
            return {"error": str(e)}

    def create_client_agent(self, business_info: dict) -> dict:
        """Create a customized agent for a client."""

        # Get template
        industry = business_info.get("industry", "generic")
        template = self.templates.get(industry, self.templates["generic"])

        # Build system prompt with client details
        ai_name = business_info.get("ai_name", "Alex")
        system_prompt = template["system_prompt"].format(
            ai_name=ai_name,
            business_name=business_info.get("business_name", "the business"),
            service_type=business_info.get("service_type", "our services"),
            service_areas=business_info.get("service_areas", "local area"),
            operating_hours=business_info.get("hours", "9am-5pm weekdays"),
            emergency_contact=business_info.get("emergency_contact", "the owner"),
            role=business_info.get("role", "team member"),
            location=business_info.get("location", ""),
            staff_names=business_info.get("staff_names", "our team")
        )

        first_message = template["greeting"].format(
            ai_name=ai_name,
            business_name=business_info.get("business_name", "our business")
        )

        # Select voice
        voice_key = business_info.get("voice", "female_au")
        voice_config = self.voices.get(voice_key, self.voices["female_au"])

        # Create agent payload
        payload = {
            "name": f"{business_info.get('business_name', 'Client')} - ReceptionistAI",
            "firstMessage": first_message,
            "firstMessageMode": "assistant-speaks-first",
            "voice": {
                **voice_config,
                "stability": 0.5,
                "similarityBoost": 0.75
            },
            "model": {
                "provider": "openai",
                "model": "gpt-4o",
                "temperature": 0.7,
                "messages": [{"role": "system", "content": system_prompt}]
            },
            "transcriber": {
                "provider": "deepgram",
                "model": "nova-3",
                "language": "en-AU"
            },
            "backgroundDenoisingEnabled": True
        }

        print(f"🤖 Creating agent for: {business_info.get('business_name')}")
        result = self._make_request("POST", "/assistant", payload)

        if "id" in result:
            print(f"✅ Agent created! ID: {result['id']}")
        else:
            print(f"❌ Failed: {result.get('error')}")

        return result

    def list_agents(self) -> list:
        """List all agents in the account."""
        print("📋 Fetching agents...")
        result = self._make_request("GET", "/assistant")

        if isinstance(result, list):
            print(f"Found {len(result)} agents:")
            for agent in result:
                print(f"   - {agent.get('name', 'Unnamed')} | ID: {agent.get('id', 'N/A')}")
            return result
        else:
            print(f"Error: {result.get('error')}")
            return []

    def get_agent(self, agent_id: str) -> dict:
        """Get details of a specific agent."""
        return self._make_request("GET", f"/assistant/{agent_id}")

    def create_test_call(self, agent_id: str, phone_number: str) -> dict:
        """Initiate a test call to verify agent."""
        print(f"📞 Initiating test call to {phone_number}...")

        payload = {
            "assistantId": agent_id,
            "customer": {
                "number": phone_number
            }
        }

        result = self._make_request("POST", "/call/phone", payload)

        if "id" in result:
            print(f"✅ Call initiated! Call ID: {result['id']}")
        else:
            print(f"❌ Failed: {result.get('error')}")

        return result


def main():
    parser = argparse.ArgumentParser(description="VAPI Client Agent Template for ReceptionistAI")
    parser.add_argument("--create", type=str, help="Create agent for business name")
    parser.add_argument("--type", type=str, default="generic", help="Industry type (trades/medical/legal/generic)")
    parser.add_argument("--list", action="store_true", help="List all agents")
    parser.add_argument("--get", type=str, help="Get agent details by ID")
    parser.add_argument("--test-call", type=str, help="Agent ID for test call")
    parser.add_argument("--phone", type=str, help="Phone number for test call")

    args = parser.parse_args()

    manager = VAPIClientTemplate()

    if args.create:
        business_info = {
            "business_name": args.create,
            "industry": args.type,
            "ai_name": "Maya",
            "service_type": args.type,
            "hours": "Monday-Friday 8am-5pm",
            "role": "team"
        }
        manager.create_client_agent(business_info)
    elif args.list:
        manager.list_agents()
    elif args.get:
        result = manager.get_agent(args.get)
        print(json.dumps(result, indent=2))
    elif args.test_call and args.phone:
        manager.create_test_call(args.test_call, args.phone)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
