# -*- coding: utf-8 -*-
import os
import subprocess
import time
import requests
from appium import webdriver
from appium.options.android import UiAutomator2Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# ==========================================
# CONFIGURATION & PARAMETERS
# ==========================================
key = 'dreYWZN6BkiImePegTZ5et'  # Replace with your IFTTT webhook key
event = 'tbn_event'             # Replace with your IFTTT event name

def send_ifttt_webhook(event, key, message):
    """Send a webhook message to IFTTT."""
    url = f'https://maker.ifttt.com/trigger/{event}/with/key/{key}'
    data = {'value1': message}
    try:
        requests.post(url, json=data, timeout=10)
        print(f"Webhook sent with message: {message}")
    except Exception as e:
        print(f"Failed to transmit webhook: {e}")
    return None

def pre_launch_wake_and_start():
    """Ensure the headless canvas is awake and force start the app.
    print("Configuring headless display environment...")
    os.environ["WAYLAND_DISPLAY"] = "wayland-0"
    os.environ["XDG_SESSION_TYPE"] = "wayland"

    print("Starting Weston headless virtual display and Waydroid session...")
    subprocess.Popen(
        ["weston", "--backend=headless-backend.so", "--socket=wayland-0"],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
    )
    time.sleep(2)
    
    subprocess.Popen(
        ["waydroid", "session", "start"],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
    )
    time.sleep(10) # Give Android UI time to fully boot"""

    print("Waking up virtual display canvas...")
    try:
        # 1. Force a fresh connection just in case ADB ghosted the TCP link
        subprocess.run("adb connect 192.168.240.2:5555", shell=True, timeout=5, stdout=subprocess.DEVNULL)
        
        # 2. Execute wakeup commands with strict timeouts
        subprocess.run("adb shell svc power stayon true", shell=True, timeout=10)
        subprocess.run("adb shell wm dismiss-keyguard", shell=True, timeout=10)

        print("Launching Verizon FamilyBase via Activity Manager...")
        subprocess.run("adb shell am start -W -n com.verizon.familybase.parent/com.verizon.familybase.MainActivity --receiver-foreground -f 0x10000000", shell=True, timeout=15)
        time.sleep(3)

        
    except subprocess.TimeoutExpired:
        print("CRITICAL: ADB command timed out! The Android network bridge is frozen.")
    time.sleep(5)

def force_close_app():
    """Force stops the Android app and spins down the headless session."""
    print("Force-stopping application package execution layers cleanly...")
    subprocess.run("adb shell am force-stop com.verizon.familybase.parent", shell=True)
    
    """"print("Tearing down Waydroid session and Weston...")
    subprocess.run(["waydroid", "session", "stop"], capture_output=True)
    subprocess.run(["pkill", "weston"], capture_output=True)
    print("System optimization cleanup complete. Session closed.")"""


def start_appium_session():
    """Initialize the cloud Appium options object matching Waydroid architecture."""
    options = UiAutomator2Options()
    options.platform_name = "Android"
    options.automation_name = "UiAutomator2"
    options.device_name = "192.168.240.2:5555"
    options.udid = "192.168.240.2:5555"
    options.app_package = "com.verizon.familybase.parent"
    options.app_wait_activity = "*" # Wait for whatever activity Monkey launched
    options.no_reset = True
    options.ensure_webviews_have_pages = True
    options.set_capability("androidHome", "/usr/lib/android-sdk")

    driver = webdriver.Remote('http://127.0.0.1:4723', options=options)
    return driver


# ==========================================
# EXECUTION PIPELINE
# ==========================================
if __name__ == "__main__":
    # Pre-wake display canvas and force app execution
    pre_launch_wake_and_start()

    # Start the Appium UI automation driver session
    driver = start_appium_session()
    print("Appium session established successfully.")

    # Define locators
    limit_locator = (By.ID, "com.verizon.familybase.parent:id/tv_dataLimitCount")
    rightArrow_locator = (By.ID, "com.verizon.familybase.parent:id/ivRightArrowData")
    changeLimit_locator = (By.ID, "com.verizon.familybase.parent:id/ll_et_limit")
    newLimit_locator = (By.ID, "com.verizon.familybase.parent:id/et_limit")
    save_locator = (By.ID, "com.verizon.familybase.parent:id/btn_save")
    edit_text_locator = (By.CLASS_NAME, "android.widget.EditText")
    # Initialization Locator
    get_started_locator = (By.XPATH, "//*[@text='Get Started']")
    get_signin_locator = (By.XPATH, "//*[@text='Sign In']")

try:
    # ==========================================
    # SMART STATE CHECK & INITIALIZATION
    # ==========================================
    print("Checking if we are already on the dashboard or if first-time setup is required...")
    try:
        # Give the app 10 seconds to load the dashboard natively
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located(limit_locator)
        )
        print("Dashboard limit detected. Skipping first-time initialization.")
    except:
        print("Dashboard not found. Intercepting first-time setup splash screen...")
        
        # 1. Look for and click 'Get Started'
        get_started_btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable(get_started_locator)
        )
        get_started_btn.click()
        print("Clicked 'Get Started'. Waiting for carrier authentication and dashboard load...")
        
        # 2. Wait for the dashboard to load after getting started
        # Increased timeout to 20s to account for background network auth
        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located(limit_locator)
        )
        print("Successfully transitioned to the dashboard!")

    # ==========================================
    # CORE AUTOMATION STEPS
    # ==========================================
    print("Executing data limit automation steps...")
    
    # Pick current usage 
    currentUsage = driver.find_element(*limit_locator).text
    usage = currentUsage.split('/')[0].strip()
    usage_float = round(float(usage), 1)
    if usage_float < 0.5:
        usage_float = 0.5
    time.sleep(2)
    
    # Click on right arrow
    driver.find_element(*rightArrow_locator).click()
    time.sleep(2)
    
    # Click on new limit
    limit_field = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable(changeLimit_locator)
    )
    time.sleep(2)
    limit_field.click()
    time.sleep(2)
    
    # Enter digits
    edit_text = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located(edit_text_locator)
    )
    time.sleep(0.5)
    
    edit_text.send_keys(" ")
    time.sleep(0.5)
    edit_text.send_keys(f"{usage_float:.1f}")
    time.sleep(3)
    
    # Submit
    driver.find_element(*save_locator).click()
    time.sleep(5)
    print("Verizon Limit Automation complete.")

except Exception as e:
    print(f"Critical execution block fault tripped: {e}")
    send_ifttt_webhook(event, key, "Mobile Limit Failed!")
    # ... (rest of your screenshot/XML triage code remains exactly the same)

    try:
        print("Snapping emergency triage screenshots and layout XML...")
        driver.save_screenshot('/home/ubuntu/verizon_fault.png')
        with open('/home/ubuntu/verizon_layout.xml', 'w', encoding='utf-8') as f:
            f.write(driver.page_source)
        print("Diagnostics saved to /home/ubuntu/verizon_fault.png and /home/ubuntu/verizon_layout.xml")
    except Exception as diag_err:
        print(f"Failed to capture diagnostics: {diag_err}")

finally:
    print("Safely disconnecting client driver stream links...")
    try:
        driver.quit()
    except:
        pass
    
    force_close_app()