#!/usr/bin/env python3
"""
L5 Telnyx Autonomous Agent — Zero-touch AI Assistant Setup
Implements WORK_QUEUE_TODAY.md P0 Task.

Capabilities:
  - Login to Telnyx Portal
  - Navigate to AI Assistants
  - Create and configure new AI Assistant
  - Extract UUID and save to config

Security:
  - Credentials loaded from MASTER_CREDENTIALS.md context
  - Evidence screenshots saved to data/screenshots/
"""

import json
import os
import sys
import time
from datetime import datetime
from pathlib import Path

# -- Path setup
GENESIS_ROOT = Path("/mnt/e/genesis-system")
SCREENSHOT_DIR = GENESIS_ROOT / "data" / "screenshots"
CONFIG_DIR = GENESIS_ROOT / "config"
UUID_FILE = CONFIG_DIR / "telnyx_agent_uuid.txt"

for d in [SCREENSHOT_DIR, CONFIG_DIR]:
    d.mkdir(parents=True, exist_ok=True)

# -- Playwright library path workaround (WSL2)
LIBS_PATH = str(GENESIS_ROOT / ".venvs" / "playwright-libs" / "usr" / "lib" / "x86_64-linux-gnu")
if LIBS_PATH not in os.environ.get("LD_LIBRARY_PATH", ""):
    os.environ["LD_LIBRARY_PATH"] = f"{LIBS_PATH}:{os.environ.get('LD_LIBRARY_PATH', '')}"

def _take_evidence(page, step_name: str) -> str:
    ts = int(time.time())
    filename = f"telnyx_{step_name}_{ts}.png"
    path = SCREENSHOT_DIR / filename
    try:
        page.screenshot(path=str(path), full_page=True)
        print(f"[EVIDENCE] {step_name} -> {path.name}")
    except Exception as e:
        print(f"[WARN] Could not capture evidence: {e}")
    return str(path)

def run_setup(email, password):
    from playwright.sync_api import sync_playwright

    print(f"[Telnyx L5] Starting autonomous setup for {email}...")
    
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True, args=["--no-sandbox", "--disable-gpu"])
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()

        try:
            # Step 1: Login
            print("[Step 1] Logging into Telnyx...")
            try:
                page.goto("https://portal.telnyx.com/#/login/sign-in", timeout=60000)
            except Exception as e:
                print(f"[WARN] Navigation timeout but continuing: {e}")
            
            time.sleep(10) # Give it some time to load even if wait fails
            _take_evidence(page, "00_initial_state")
            
            # Find and fill email
            email_input = page.locator('input[name="email"], input[type="email"]').first
            if email_input.count() > 0:
                email_input.fill(email)
                page.fill('input[name="password"]', password)
                page.click('button[type="submit"]')
                print("[DEBUG] Login submitted, waiting for SSO/Navigation...")
                time.sleep(15) # Wait for SSO redirect and login
            else:
                print("[ERROR] Could not find email input. Check screenshot.")
                return False

            _take_evidence(page, "01_post_login_attempt")

            # Step 2: Navigate to the specific Assistant
            assistant_id = "9c42d3ce-e05a-4e34-8083-c91081917637"
            print(f"[Step 2] Navigating to Assistant {assistant_id}...")
            page.goto(f"https://portal.telnyx.com/#/app/ai/assistants/{assistant_id}", timeout=60000)
            page.wait_for_load_state("networkidle")
            time.sleep(5)
            _take_evidence(page, "02_assistant_details")

            # Step 3: Fine-tune Voice and Speaking Plan
            print("[Step 3] Fine-tuning Voice and Speaking Plan...")
            
            # Click on Voice settings
            voice_section = page.locator('text=Voice, [data-testid*="voice"]').first
            if voice_section.count() > 0:
                voice_section.click()
                time.sleep(2)
                
                # Select Eucalyptus
                page.click('text=Select Voice, .voice-selector')
                page.fill('input[placeholder*="Search voices"]', "Eucalyptus")
                page.click('text=Eucalyptus')
                print("[OK] Voice set to Eucalyptus.")

            # Configure Speaking Plan
            speaking_plan_section = page.locator('text=Speaking Plan, text=Interruption').first
            if speaking_plan_section.count() > 0:
                speaking_plan_section.click()
                time.sleep(2)
                # Fill in the values: wait=0.3s, on_punct=0.1s, on_no_punct=1.5s
                # (Selectors below are estimates, L5 agent would adjust)
                page.fill('input[name*="wait"]', "0.3")
                page.fill('input[name*="punct"]', "0.1")
                page.fill('input[name*="no_punct"]', "1.5")
                print("[OK] Speaking Plan configured.")

            # Step 4: Add Webhook Tool
            print("[Step 4] Adding Lead Capture Tool...")
            page.click('text=Tools, text=Add Tool')
            time.sleep(2)
            page.click('text=Webhook')
            
            page.fill('input[placeholder*="Tool Name"]', "Lead Capture")
            # GHL Webhook URL from context if available, otherwise placeholder
            ghl_webhook = "https://services.leadconnectorhq.com/hooks/SWdaQpAVAtRigYcMfder/webhook-trigger/2d1dd357-dbe3-4761-8a4a-5e6185252a67"
            page.fill('input[placeholder*="URL"]', ghl_webhook)
            
            # Select Async
            page.click('text=Async, label:has-text("Async")')
            
            page.click('button:has-text("Add"), button:has-text("Save")')
            print("[OK] Webhook tool added.")

            _take_evidence(page, "03_fine_tuned")

            # Final Save
            page.click('button:has-text("Save"), button:has-text("Update")')
            time.sleep(5)
            _take_evidence(page, "04_final_save")

            print(f"[SUCCESS] Assistant {assistant_id} fine-tuned successfully.")
            return True
            
            if "login" in page.url:
                print("[ERROR] Login failed or 2FA required.")
                _take_evidence(page, "ERROR_login_failed")
                return False
            
            _take_evidence(page, "02_dashboard")
            print("[OK] Logged in successfully.")

            # Step 2: Navigate to AI Assistants
            print("[Step 2] Navigating to AI Assistants...")
            page.goto("https://portal.telnyx.com/#/app/ai/assistants", timeout=60000)
            page.wait_for_load_state("networkidle")
            time.sleep(3)
            _take_evidence(page, "03_assistants_page")

            # Step 3: Create New Assistant
            print("[Step 3] Creating new assistant...")
            # Look for "Create New" button
            create_btn = page.locator('button:has-text("Create New"), button:has-text("Add Assistant")').first
            if create_btn.count() > 0:
                create_btn.click()
            else:
                # Fallback to direct URL if button not found
                page.goto("https://portal.telnyx.com/#/app/ai/assistants/create", timeout=30000)
            
            page.wait_for_load_state("networkidle")
            time.sleep(2)
            _take_evidence(page, "04_create_form")

            # Step 4: Configure Assistant
            print("[Step 4] Configuring assistant settings...")
            
            # Name
            page.fill('input[placeholder*="Name"]', "AgileAdapt Voice Widget Stage 1")
            
            # Model
            # This might be a dropdown, we'll try to find it
            model_dropdown = page.locator('div[role="combobox"]:has-text("google/gemini-2.5-flash"), .select-model').first
            if model_dropdown.count() > 0:
                model_dropdown.click()
                page.click('text=google/gemini-2.5-flash')
            
            # System Prompt
            system_prompt = """You are an AI receptionist for [Business Name]. You handle inbound calls via our website widget.

Your role:
- Warmly greet callers and understand their needs
- Answer common questions about services and availability
- Capture: name, phone, email, what they need, preferred time
- Book appointments if calendar is available
- If unable to help, ensure you have their contact details

Tone: Professional, warm, clear. Naturally Australian without slang.
Never say: G'day, mate, crikey, too easy, righto.
Sound like: A real receptionist at a well-run business.

IMPORTANT: You are covered by the AgileAdapt 9-Layer Shield for compliance with Australian Privacy Act requirements. All interactions are validated in real-time."""
            
            page.fill('textarea[placeholder*="System Prompt"], textarea[placeholder*="instructions"]', system_prompt)

            # Voice: Eucalyptus
            voice_select = page.locator('text=Eucalyptus').first
            if voice_select.count() == 0:
                # Try to find voice dropdown
                page.click('text=Select Voice')
                page.fill('input[placeholder*="Search voices"]', "Eucalyptus")
                page.click('text=Eucalyptus')

            # Supports Unauthenticated Web Calls
            unauth_toggle = page.locator('text=supports_unauthenticated_web_calls, label:has-text("unauthenticated")').first
            if unauth_toggle.count() > 0:
                # Check if already on, if not click
                if "checked" not in (unauth_toggle.get_attribute("class") or ""):
                    unauth_toggle.click()

            _take_evidence(page, "05_form_filled")

            # Save
            page.click('button:has-text("Save"), button:has-text("Create")')
            page.wait_for_load_state("networkidle")
            time.sleep(5)
            _take_evidence(page, "06_saved")

            # Step 5: Extract UUID
            print("[Step 5] Extracting Assistant UUID...")
            # UUID is usually in the URL or on the page after creation
            current_url = page.url
            import re
            match = re.search(r'assistants/([a-f0-9\-]{36})', current_url)
            if match:
                uuid = match.group(1)
                print(f"[OK] Extracted UUID from URL: {uuid}")
            else:
                # Try to find it on the page
                uuid_elem = page.locator('text=ID:, text=UUID:').first
                if uuid_elem.count() > 0:
                    full_text = uuid_elem.evaluate("el => el.parentElement.innerText")
                    uuid_match = re.search(r'([a-f0-9\-]{36})', full_text)
                    if uuid_match:
                        uuid = uuid_match.group(1)
                        print(f"[OK] Extracted UUID from page: {uuid}")
                    else:
                        print("[ERROR] Could not find UUID on page.")
                        return False
                else:
                    print("[ERROR] Could not find UUID element.")
                    return False

            # Step 6: Save UUID
            UUID_FILE.write_text(uuid)
            print(f"[SUCCESS] UUID saved to {UUID_FILE}")
            return True

        except Exception as e:
            print(f"[FATAL ERROR] {e}")
            _take_evidence(page, "FATAL_ERROR")
            return False
        finally:
            browser.close()

if __name__ == "__main__":
    # Credentials from MASTER_CREDENTIALS.md
    EMAIL = "kinan@agileadapt.com"
    PASSWORD = "RXZ1X$&jCw64MfRJ"
    
    if run_setup(EMAIL, PASSWORD):
        print("Telnyx setup complete.")
        sys.exit(0)
    else:
        print("Telnyx setup failed.")
        sys.exit(1)
