#!/usr/bin/env python3
"""GHL Conversation AI setup via API (direct, no Playwright)"""
import os, json, sys, requests
from datetime import datetime
from pathlib import Path

GHL_EMAIL = os.getenv('GHL_EMAIL', 'kinan@agileadpt.com')
GHL_PASSWORD = os.getenv('GHL_PASSWORD', 'SystemBird505*')
LOCATION_ID = os.getenv('LOCATION_ID', 'SWdaQpAVAtRigYcMfder')
REPORT_DIR = Path(f'/mnt/e/genesis-system/reports/ghl_api_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
REPORT_DIR.mkdir(parents=True, exist_ok=True)

BOT_NAME = "Bunker FNQ AI Receptionist"
BOT_PERSONA = """You are the friendly AI receptionist for Bunker FNQ, a concreting business in Kuranda, Queensland. 
You help potential clients by answering questions about concrete driveways, slabs, paths and patios.
Always offer to book a free quote. Be warm, professional, and Australian in tone.
Business hours: Mon-Fri 7am-5pm. Phone: 0424 459 772."""

def run():
    results = []
    
    try:
        results.append("=== GHL Conversation AI API Setup ===")
        results.append(f"Email: {GHL_EMAIL}")
        results.append(f"Location ID: {LOCATION_ID}")
        
        # Step 1: Login via API
        results.append("\n[1] Authenticating...")
        login_url = 'https://api.gohighlevel.com/auth/login'
        login_payload = {
            'email': GHL_EMAIL,
            'password': GHL_PASSWORD
        }
        
        resp = requests.post(login_url, json=login_payload, timeout=10)
        results.append(f"Login response: {resp.status_code}")
        
        if resp.status_code != 200:
            results.append(f"ERROR: Login failed: {resp.text}")
            return results
        
        auth_data = resp.json()
        access_token = auth_data.get('token') or auth_data.get('accessToken')
        results.append(f"Auth token: {access_token[:20]}..." if access_token else "ERROR: No token in response")
        
        headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
        
        # Step 2: Get location details
        results.append("\n[2] Fetching location...")
        loc_resp = requests.get(f'https://api.gohighlevel.com/v1/locations/{LOCATION_ID}', 
                               headers=headers, timeout=10)
        results.append(f"Location response: {loc_resp.status_code}")
        if loc_resp.status_code == 200:
            results.append(f"Location data: {json.dumps(loc_resp.json(), indent=2)[:500]}")
        
        # Step 3: Create or update Conversation AI bot
        results.append("\n[3] Setting up Conversation AI bot...")
        
        # Check if bot exists
        bot_list_url = f'https://api.gohighlevel.com/v1/locations/{LOCATION_ID}/conversations/ai-bots'
        bot_list_resp = requests.get(bot_list_url, headers=headers, timeout=10)
        results.append(f"Bot list response: {bot_list_resp.status_code}")
        
        if bot_list_resp.status_code == 200:
            bots = bot_list_resp.json().get('data', [])
            results.append(f"Existing bots: {len(bots)}")
            for bot in bots[:3]:
                results.append(f"  - {bot.get('name', 'Unknown')}")
        
        # Create new bot
        results.append("\n[4] Creating new Conversation AI bot...")
        bot_payload = {
            'name': BOT_NAME,
            'systemPrompt': BOT_PERSONA,
            'model': 'gpt-4o-mini',
            'temperature': 0.7,
            'maxTokens': 500,
            'enabled': True
        }
        
        create_url = f'https://api.gohighlevel.com/v1/locations/{LOCATION_ID}/conversations/ai-bots'
        create_resp = requests.post(create_url, json=bot_payload, headers=headers, timeout=10)
        results.append(f"Create bot response: {create_resp.status_code}")
        results.append(f"Response: {create_resp.text[:300]}")
        
        if create_resp.status_code in [200, 201]:
            bot_id = create_resp.json().get('data', {}).get('id')
            results.append(f"SUCCESS: Bot created with ID: {bot_id}")
        else:
            results.append(f"Bot creation failed: {create_resp.status_code}")
        
        results.append("\n=== Report saved ===")
        
    except Exception as e:
        import traceback
        results.append(f"\nERROR: {str(e)}")
        results.append(traceback.format_exc())
    
    # Save report
    with open(REPORT_DIR/'report.json', 'w') as f:
        json.dump({'results': results, 'ts': datetime.now().isoformat()}, f, indent=2)
    
    with open(REPORT_DIR/'report.txt', 'w') as f:
        f.write('\n'.join(results))
    
    for r in results:
        print(r)
    
    return results

if __name__ == '__main__':
    run()
