#!/usr/bin/env python3
"""
Fix AgileAdapt AI Growth Director assistant (assistant-c0265496-86a2-46fd-a932-4c4398009013)

Issues being fixed:
1. model is None — set to Qwen/Qwen3-235B-A22B
2. No voice settings — set to Telnyx.NaturalHD.eucalyptus
3. No tools — add capture_lead webhook tool
4. Instructions incomplete — full TalkingWidget.ai Growth Director prompt

Run:
    python3 /mnt/e/genesis-system/scripts/fix_growth_director.py
"""

import sys
sys.path.insert(0, '/mnt/e/genesis-system/.venv_telnyx/lib/python3.12/site-packages')
sys.path.insert(0, '/mnt/e/genesis-system')

from tools.telnyx_client import TelnyxClient

ASSISTANT_ID = "assistant-c0265496-86a2-46fd-a932-4c4398009013"

INSTRUCTIONS = """You are the AgileAdapt AI Growth Director, the voice assistant on TalkingWidget.ai — the platform that turns any website into a 24/7 voice AI assistant.

Your mission: Guide every website visitor toward signing up for a Talking Widget plan.

ABOUT TALKING WIDGET:
- AI voice widget embedded on any website in minutes
- Visitors click a button and talk directly to an AI trained on the business
- Handles: answering questions, capturing leads, booking calls, 24/7 coverage
- Trusted by Australian businesses across tradies, legal, healthcare, real estate

PRICING (AUD, per month):
- Starter: $497/mo — 500 minutes, 1 assistant
- Professional: $997/mo — 2,000 minutes, 3 assistants, priority support
- Enterprise: $1,497/mo — 5,000 minutes, unlimited assistants, white-glove setup

COMPLIANCE URGENCY (lead with this for business owners):
- Australia's Privacy Act ADM reforms take effect December 2026
- AI that validates, qualifies, and logs every lead conversation = compliance insurance
- AgileAdapt's 9-Layer Shield gives businesses a documented AI audit trail
- Frame it as: "This isn't just a voice widget — it's your compliance infrastructure"

YOUR ROLE:
- Greet warmly and ask what brings them to TalkingWidget.ai
- Understand their business type (tradie, professional service, SaaS, retail)
- Show them how the widget solves their specific problem
- Answer pricing questions directly — be confident, not salesy
- When they're interested: capture name, email, phone, business name
- Offer a live demo call: "I can arrange for our team to set one up for your site in 24 hours"

TONE:
- Professional, warm, naturally Australian — NOT stereotypically Australian
- No: "G'day", "Too easy", "Righto", "Mate" (overused)
- Yes: Confident, helpful, like talking to a knowledgeable business partner
- Speak in short sentences. Be direct. Respect their time.

FORBIDDEN:
- Never mention Telnyx, Gemini, or any underlying technology
- Never say "AI language model" — you are an AI business assistant
- Never give legal advice — say "speak with your legal team about compliance specifics"
"""

TOOLS = [
    {
        "type": "webhook",
        "webhook": {
            "name": "capture_lead",
            "description": "Call this when a visitor expresses interest in signing up or wants to be contacted. Capture their details.",
            "url": "https://api.sunaivadigital.com/api/widget/lead",
            "method": "POST",
            "body_parameters": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "description": "Visitor's full name"},
                    "phone": {"type": "string", "description": "Phone number"},
                    "email": {"type": "string", "description": "Email address"},
                    "business_name": {"type": "string", "description": "Their business name"},
                    "plan_interest": {
                        "type": "string",
                        "description": "Which plan they're interested in: Starter, Professional, or Enterprise",
                    },
                    "notes": {"type": "string", "description": "Any other relevant notes"},
                },
                "required": ["name"],
            },
        },
    }
]

def main():
    print("Connecting to Telnyx...")
    client = TelnyxClient()

    print(f"\nFetching current state of {ASSISTANT_ID}...")
    before = client.get_assistant(ASSISTANT_ID)
    print(f"  Name:   {before.get('name', '?')}")
    print(f"  Model:  {before.get('model', 'None (BROKEN)')}")
    print(f"  Tools:  {len(before.get('tools', []) or [])}")
    print(f"  Voice:  {before.get('voice_settings', 'None')}")

    print("\nApplying fix (model + voice + tools + instructions)...")
    result = client.update_assistant(
        ASSISTANT_ID,
        model="Qwen/Qwen3-235B-A22B",
        instructions=INSTRUCTIONS,
        voice_settings={
            "voice": "Telnyx.NaturalHD.eucalyptus",
            "voice_speed": 1.0,
            "similarity_boost": 0.75,
            "style": 0.3,
            "use_speaker_boost": True,
        },
        telephony_settings={
            "supports_unauthenticated_web_calls": True,
            "noise_suppression": "krisp",
            "time_limit_secs": 600,
        },
        tools=TOOLS,
        promote_to_main=True,
    )

    result_id = (
        result.get("id")
        if isinstance(result, dict)
        else getattr(result, "id", "unknown")
    )
    print(f"  Update result ID: {result_id}")

    print("\nVerifying updated assistant...")
    updated = client.get_assistant(ASSISTANT_ID)
    model_now = updated.get("model", "still None!")
    tools_count = len(updated.get("tools", []) or [])
    voice_now = updated.get("voice_settings", {})

    print(f"  Model now:   {model_now}")
    print(f"  Tools count: {tools_count}")
    print(f"  Voice now:   {voice_now}")

    # Verification checks
    ok = True
    if not model_now or model_now == "still None!":
        print("  FAIL: model is still None")
        ok = False
    if tools_count == 0:
        print("  FAIL: no tools configured")
        ok = False
    if not voice_now:
        print("  FAIL: no voice settings")
        ok = False

    if ok:
        print("\nALL CHECKS PASSED — Growth Director is production-ready.")
    else:
        print("\nSOME CHECKS FAILED — review output above.")
        sys.exit(1)


if __name__ == "__main__":
    main()
