#!/usr/bin/env python3
"""
GHL Setup Script for Bunker FNQ Demo
"""

import sys
import time
from pathlib import Path

# Add genesis-system to python path
sys.path.append(str(Path(__file__).resolve().parent.parent))

from scripts.browser_agent import BrowserAgent

# --- CONFIGURATION ---
GHL_USER = "kinan@agileadpt.com"
GHL_PASS = "SystemBird505*"
GHL_URL = "https://app.gohighlevel.com"
LOCATION_ID = "SWdaQpAVAtRigYcMfder"
SUB_ACCOUNT_URL = f"{GHL_URL}/v2/location/{LOCATION_ID}/dashboard"

def login_to_ghl(agent: BrowserAgent):
    """Logs into GoHighLevel."""
    print("Navigating to GHL login page...")
    agent.navigate(GHL_URL)
    time.sleep(5) # Wait for page to settle

    print("Entering credentials...")
    agent.page.fill('input[name="email"]', GHL_USER)
    time.sleep(1)
    agent.page.fill('input[name="password"]', GHL_PASS)
    time.sleep(1)
    
    print("Clicking login button...")
    agent.page.click('button[type="submit"]')
    
    # Wait for navigation to the dashboard after login
    print("Waiting for dashboard to load...")
    try:
        agent.page.wait_for_url("**/dashboard", timeout=120000)
        print("Login successful.")
        agent.screenshot("login_successful.png")
        return True
    except Exception as e:
        print(f"Login failed. Could not find dashboard URL after login. Error: {e}")
        agent.screenshot("login_failed.png")
        return False

def switch_to_subaccount(agent: BrowserAgent):
    """Switches to the specified GHL sub-account."""
    print(f"Navigating to sub-account: {SUB_ACCOUNT_URL}")
    agent.navigate(SUB_ACCOUNT_URL)
    try:
        agent.page.wait_for_url(f"**/{LOCATION_ID}/dashboard", timeout=60000)
        print("Successfully switched to sub-account.")
        return True
    except Exception as e:
        print(f"Failed to switch to sub-account. Error: {e}")
        agent.screenshot("subaccount_switch_failed.png")
        return False

def activate_workflows(agent: BrowserAgent):
    """Activates the draft workflows."""
    print("Navigating to workflows page...")
    workflows_url = f"{GHL_URL}/v2/location/{LOCATION_ID}/automation/workflow"
    agent.navigate(workflows_url)
    time.sleep(5) # Wait for workflows to load

    workflows_to_activate = [
        "B-008-WF-1.1. Webchat",
        "B-008-WF-0.1. Segment Inbound MSG",
        "B-008-WF-4.1. Contact Us Form"
    ]

    for workflow_name in workflows_to_activate:
        print(f"Activating workflow: {workflow_name}")
        try:
            # Find the row corresponding to the workflow
            row_selector = f'//tr[.//a[normalize-space(.)="{workflow_name}"]]'
            workflow_row = agent.page.wait_for_selector(row_selector, timeout=30000)

            # Check if it's already active
            status_element = workflow_row.query_selector('//span[contains(@class, "status")]')
            status_text = status_element.inner_text() if status_element else ""
            
            if "active" in status_text.lower() or "published" in status_text.lower():
                print(f"Workflow '{workflow_name}' is already active.")
                continue

            # Click the three-dots menu to open the dropdown
            menu_button = workflow_row.query_selector('//button[contains(@id, "dropdown")]')
            if not menu_button:
                 # if the id does not contain dropdown, try another selector
                 menu_button = workflow_row.query_selector('//button[contains(@class, "dropdown")]')
            
            if menu_button:
                menu_button.click()
                time.sleep(1)

                # Click the 'Publish' or 'Activate' button from the dropdown
                # Using a generic selector that might cover both cases
                publish_button = agent.page.locator('//a[normalize-space(.)="Publish"] | //button[normalize-space(.)="Make Active"]')
                if publish_button.count() > 0:
                    publish_button.first.click()
                    print(f"Clicked 'Publish' for {workflow_name}")
                    time.sleep(2) # Wait for status to update
                else:
                    print(f"Could not find 'Publish' or 'Activate' button for {workflow_name}.")
            else:
                print(f"Could not find menu button for {workflow_name}")

        except Exception as e:
            print(f"Could not activate workflow '{workflow_name}'. Error: {e}")
            agent.screenshot(f"workflow_activation_failed_{workflow_name.replace(' ', '_')}.png")

    print("Finished workflow activation.")
    return True

def configure_conversation_ai(agent: BrowserAgent):
    """Configures the Conversation AI settings."""
    print("Navigating to Conversation AI page...")
    convo_ai_url = f"{GHL_URL}/v2/location/{LOCATION_ID}/settings/conversation-ai"
    agent.navigate(convo_ai_url)
    time.sleep(5)

    try:
        # Enable Conversation AI
        print("Enabling Conversation AI...")
        # This selector is a guess. It might be a toggle switch.
        enable_switch = agent.page.locator('//label[contains(., "Enable Conversation AI")]/following-sibling::div//input[@type="checkbox"]')
        if not enable_switch.is_checked():
            enable_switch.check()
            print("Conversation AI enabled.")
            time.sleep(1)

        # Set Persona
        print("Setting AI persona...")
        persona_text = """You are the AI assistant for Bunker FNQ, a concreting business in Kuranda QLD.

Services we offer:
- Underground bunkers and cyclone shelters
- Wine cellars and storage rooms
- General concreting, driveways, and slabs
- Retaining walls and headwalls
- Commercial concrete work

Owner: George
Phone: 0424 459 772
Location: Kuranda QLD 4881
Service areas: Cairns, Port Douglas, Redlynch, Cooktown, Tablelands

Your goal: Qualify leads by asking what service they need, when they need it, and where the job is located. Then either book an appointment or capture their details for George to follow up.

Tone: Professional but friendly. Australian. Down-to-earth."""
        # This selector is a guess
        persona_textarea = agent.page.locator('textarea[placeholder*="persona"]')
        persona_textarea.fill(persona_text)

        # Set Response Style
        print("Setting response style...")
        style_text = "Professional but friendly, Australian tone"
        # This selector is a guess
        style_textarea = agent.page.locator('textarea[placeholder*="style"]')
        style_textarea.fill(style_text)
        
        # Set Goal
        print("Setting AI goal...")
        goal_text = "Qualify leads (what service, when, where) → book appointment or capture details"
        # This selector is a guess
        goal_textarea = agent.page.locator('textarea[placeholder*="goal"]')
        goal_textarea.fill(goal_text)

        # Save Changes
        print("Saving Conversation AI settings...")
        save_button = agent.page.locator('button:has-text("Save")')
        save_button.click()
        time.sleep(3)
        
        print("Conversation AI configured successfully.")
        return True
    except Exception as e:
        print(f"Could not configure Conversation AI. Error: {e}")
        agent.screenshot("convo_ai_config_failed.png")
        return False

def build_website(agent: BrowserAgent):
    """Builds the GHL website for Bunker FNQ."""
    print("Navigating to websites page...")
    websites_url = f"{GHL_URL}/v2/location/{LOCATION_ID}/funnels-and-websites"
    agent.navigate(websites_url)
    time.sleep(5)

    try:
        # This is a complex task that will likely require vision.
        # For now, we will just navigate to the page and take a screenshot.
        print("Taking screenshot of websites page for analysis.")
        agent.screenshot("websites_page.png")
        
        # Here we would use the vision agent to analyze the page
        # and decide on the next steps.
        # For example:
        # analysis = agent.analyze_page("Find the 'Create New Website' button.")
        # and then parse the analysis to get the coordinates of the button and click it.
        
        print("Website building logic would be implemented here.")
        
        return True
    except Exception as e:
        print(f"Could not build website. Error: {e}")
        agent.screenshot("website_build_failed.png")
        return False

def configure_review_widget(agent: BrowserAgent):
    """Configures the review widget."""
    print("Navigating to Reputation Management page...")
    reputation_url = f"{GHL_URL}/v2/location/{LOCATION_ID}/reputation/dashboard"
    agent.navigate(reputation_url)
    time.sleep(5)

    try:
        # This is another complex task that will likely require vision.
        # For now, we will just navigate to the page and take a screenshot.
        print("Taking screenshot of Reputation Management page for analysis.")
        agent.screenshot("reputation_page.png")

        print("Review widget configuration logic would be implemented here.")

        return True
    except Exception as e:
        print(f"Could not configure review widget. Error: {e}")
        agent.screenshot("review_widget_config_failed.png")
        return False

def configure_calendar(agent: BrowserAgent):
    """Configures the calendar."""
    print("Navigating to Calendars page...")
    calendars_url = f"{GHL_URL}/v2/location/{LOCATION_ID}/calendars/dashboard"
    agent.navigate(calendars_url)
    time.sleep(5)

    try:
        # This is another complex task that will likely require vision.
        print("Taking screenshot of Calendars page for analysis.")
        agent.screenshot("calendars_page.png")

        print("Calendar configuration logic would be implemented here.")

        return True
    except Exception as e:
        print(f"Could not configure calendar. Error: {e}")
        agent.screenshot("calendar_config_failed.png")
        return False

def verify_mctb_setup(agent: BrowserAgent):
    """Verifies the Missed Call Text-Back setup."""
    print("Navigating to workflows page...")
    workflows_url = f"{GHL_URL}/v2/location/{LOCATION_ID}/automation/workflow"
    agent.navigate(workflows_url)
    time.sleep(5)

    try:
        # This is another complex task that will likely require vision.
        print("Taking screenshot of Workflows page for analysis.")
        agent.screenshot("workflows_page_for_mctb.png")

        print("MCTB setup verification logic would be implemented here.")

        return True
    except Exception as e:
        print(f"Could not verify MCTB setup. Error: {e}")
        agent.screenshot("mctb_verification_failed.png")
        return False

def check_crm_phone_pro(agent: BrowserAgent):
    """Checks if CRM Phone Pro is installed."""
    print("Navigating to App Marketplace...")
    marketplace_url = f"{GHL_URL}/v2/location/{LOCATION_ID}/marketplace"
    agent.navigate(marketplace_url)
    time.sleep(5)

    try:
        print("Searching for CRM Phone Pro...")
        # This selector is a guess
        search_input = agent.page.locator('input[placeholder*="Search"]')
        search_input.fill("CRM Phone Pro")
        time.sleep(2)

        # This selector is a guess
        installed_text = agent.page.locator('//div[contains(text(), "CRM Phone Pro")]/following-sibling::div[contains(text(), "Installed")]')
        if installed_text.count() > 0:
            print("CRM Phone Pro is already installed.")
        else:
            print("CRM Phone Pro is not installed. Please install it manually.")
        
        return True
    except Exception as e:
        print(f"Could not check for CRM Phone Pro. Error: {e}")
        agent.screenshot("crm_phone_pro_check_failed.png")
        return False

def main():
    """
    Main function to perform GHL setup.
    """
    agent = BrowserAgent(headless=False)
    try:
        agent.start()

        if login_to_ghl(agent):
            if switch_to_subaccount(agent):
                if activate_workflows(agent):
                    print("All workflows activated successfully.")
                else:
                    print("Workflow activation failed.")
                
                if configure_conversation_ai(agent):
                    print("Conversation AI configured successfully.")
                else:
                    print("Conversation AI configuration failed.")
                
                if build_website(agent):
                    print("Website build initiated.")
                else:
                    print("Website build failed.")

                if configure_review_widget(agent):
                    print("Review widget configuration initiated.")
                else:
                    print("Review widget configuration failed.")

                if configure_calendar(agent):
                    print("Calendar configuration initiated.")
                else:
                    print("Calendar configuration failed.")

                if verify_mctb_setup(agent):
                    print("MCTB setup verification initiated.")
                else:
                    print("MCTB setup verification failed.")

                if check_crm_phone_pro(agent):
                    print("CRM Phone Pro check completed.")
                else:
                    print("CRM Phone Pro check failed.")

                input("Press Enter to continue after you are done with manual actions...")

    except Exception as e:
        print(f"An error occurred: {e}")
        agent.screenshot("main_error.png")
    finally:
        agent.stop()
if __name__ == "__main__":
    main()
