#!/usr/bin/env python3
"""
NameSilo API Key Retrieval Script
This script helps you log into NameSilo and retrieve your API key.
"""

import time
import sys
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

def get_namesilo_api_key(username, password):
    """
    Log into NameSilo and retrieve the API key.

    Args:
        username: Your NameSilo username
        password: Your NameSilo password

    Returns:
        The API key if successful, None otherwise
    """
    # Set up Firefox options for headless mode
    firefox_options = Options()
    firefox_options.add_argument('--headless')
    firefox_options.add_argument('--no-sandbox')
    firefox_options.add_argument('--disable-dev-shm-usage')
    firefox_options.add_argument('--disable-gpu')

    # Set up the service
    service = Service('/usr/local/bin/geckodriver')

    driver = None
    try:
        # Initialize the WebDriver
        print("Initializing Firefox browser...")
        driver = webdriver.Firefox(service=service, options=firefox_options)
        driver.set_page_load_timeout(60)

        # Navigate to login page
        print("Navigating to NameSilo login page...")
        driver.get("https://www.namesilo.com/login")

        # Wait for the page to load
        time.sleep(5)

        # Save screenshot of login page
        driver.save_screenshot("/root/namesilo_login_page.png")
        print("Login page screenshot saved to: /root/namesilo_login_page.png")

        # Try different field name variations
        print("Searching for login form fields...")
        username_field = None
        password_field = None

        # Try multiple selectors for username field
        username_selectors = [
            (By.NAME, "email"),
            (By.NAME, "username"),
            (By.ID, "email"),
            (By.ID, "username"),
            (By.XPATH, "//input[@type='email']"),
            (By.XPATH, "//input[@type='text' and contains(@name, 'email')]"),
            (By.XPATH, "//input[@type='text' and contains(@name, 'user')]"),
        ]

        for selector_type, selector_value in username_selectors:
            try:
                username_field = WebDriverWait(driver, 5).until(
                    EC.presence_of_element_located((selector_type, selector_value))
                )
                print(f"Found username field using: {selector_type} = {selector_value}")
                break
            except:
                continue

        if not username_field:
            print("Could not find username field. Saving page source for debugging...")
            with open("/root/namesilo_login_page_source.html", "w") as f:
                f.write(driver.page_source)
            print("Page source saved to: /root/namesilo_login_page_source.html")
            return None

        # Try multiple selectors for password field
        password_selectors = [
            (By.NAME, "password"),
            (By.ID, "password"),
            (By.XPATH, "//input[@type='password']"),
        ]

        for selector_type, selector_value in password_selectors:
            try:
                password_field = driver.find_element(selector_type, selector_value)
                print(f"Found password field using: {selector_type} = {selector_value}")
                break
            except:
                continue

        if not password_field:
            print("Could not find password field.")
            return None

        # Enter credentials
        print("Entering credentials...")
        username_field.clear()
        username_field.send_keys(username)
        time.sleep(1)

        password_field.clear()
        password_field.send_keys(password)
        time.sleep(1)

        # Find and click submit button
        print("Looking for login button...")
        submit_button = None
        submit_selectors = [
            (By.XPATH, "//button[@type='submit']"),
            (By.XPATH, "//input[@type='submit']"),
            (By.XPATH, "//button[contains(text(), 'Login')]"),
            (By.XPATH, "//button[contains(text(), 'Sign in')]"),
        ]

        for selector_type, selector_value in submit_selectors:
            try:
                submit_button = driver.find_element(selector_type, selector_value)
                print(f"Found submit button using: {selector_type} = {selector_value}")
                break
            except:
                continue

        if submit_button:
            try:
                # Try to close any popups or overlays first
                try:
                    close_buttons = driver.find_elements(By.XPATH, "//button[contains(@class, 'close') or contains(@aria-label, 'close')]")
                    for btn in close_buttons:
                        if btn.is_displayed():
                            btn.click()
                            time.sleep(1)
                except:
                    pass

                # Try clicking with JavaScript instead
                print("Clicking submit button with JavaScript...")
                driver.execute_script("arguments[0].click();", submit_button)
            except Exception as e:
                print(f"JavaScript click failed: {e}, trying regular click...")
                try:
                    submit_button.click()
                except:
                    print("Regular click failed, trying form submit...")
                    password_field.submit()
        else:
            print("No submit button found, trying form submit...")
            password_field.submit()

        print("Logging in...")
        time.sleep(7)

        # Save screenshot after login
        driver.save_screenshot("/root/namesilo_after_login.png")
        print("After-login screenshot saved to: /root/namesilo_after_login.png")

        # Check if login was successful by looking for error messages
        try:
            error_elements = driver.find_elements(By.XPATH, "//*[contains(@class, 'error') or contains(@class, 'alert')]")
            for error in error_elements:
                if error and error.is_displayed():
                    print(f"Possible error message: {error.text}")
        except:
            pass

        # Navigate to API manager page
        print("Navigating to API Manager page...")
        driver.get("https://www.namesilo.com/account/api-manager")

        # Wait for the page to load
        time.sleep(7)

        # Save screenshot of API page
        driver.save_screenshot("/root/namesilo_api_page.png")
        print("API page screenshot saved to: /root/namesilo_api_page.png")

        # Try to find the API key on the page
        print("Searching for API key...")

        # Method 1: Look for input fields or text areas containing the key
        try:
            api_key_elements = driver.find_elements(By.XPATH, "//input[@type='text']")
            for element in api_key_elements:
                value = element.get_attribute('value')
                if value and len(value) > 20:  # API keys are typically long
                    print(f"\n{'='*60}")
                    print("API Key found:")
                    print(f"{'='*60}")
                    print(value)
                    print(f"{'='*60}\n")
                    return value
        except Exception as e:
            print(f"Method 1 error: {e}")

        # Method 2: Look for readonly input fields
        try:
            api_key_elements = driver.find_elements(By.XPATH, "//input[@readonly]")
            for element in api_key_elements:
                value = element.get_attribute('value')
                if value and len(value) > 20:
                    print(f"\n{'='*60}")
                    print("API Key found (readonly field):")
                    print(f"{'='*60}")
                    print(value)
                    print(f"{'='*60}\n")
                    return value
        except Exception as e:
            print(f"Method 2 error: {e}")

        # Method 3: Look for code/pre tags
        try:
            code_elements = driver.find_elements(By.TAG_NAME, "code")
            for element in code_elements:
                text = element.text.strip()
                if text and len(text) > 20 and len(text) < 100:
                    print(f"\n{'='*60}")
                    print("Potential API Key found in code tag:")
                    print(f"{'='*60}")
                    print(text)
                    print(f"{'='*60}\n")
                    return text
        except Exception as e:
            print(f"Method 3 error: {e}")

        # Method 4: Look for any long alphanumeric strings
        try:
            import re
            page_text = driver.page_source
            # Look for strings that look like API keys (long alphanumeric strings)
            api_key_pattern = r'\b[a-zA-Z0-9]{30,}\b'
            matches = re.findall(api_key_pattern, page_text)
            if matches:
                print(f"\nFound {len(matches)} potential API key(s):")
                for i, match in enumerate(matches[:5], 1):  # Show first 5
                    print(f"{i}. {match}")
                    if i == 1:  # Return the first one
                        return match
        except Exception as e:
            print(f"Method 4 error: {e}")

        # Save page source for debugging
        with open("/root/namesilo_api_page_source.html", "w") as f:
            f.write(driver.page_source)
        print("API page source saved to: /root/namesilo_api_page_source.html")

        return None

    except Exception as e:
        print(f"Error occurred: {e}")
        import traceback
        traceback.print_exc()
        return None

    finally:
        if driver:
            print("\nClosing browser...")
            driver.quit()

def main():
    """Main function to run the script."""
    print("NameSilo API Key Retrieval Tool")
    print("="*60)

    # Get credentials from environment variables or user input
    username = os.environ.get('NAMESILO_USERNAME')
    password = os.environ.get('NAMESILO_PASSWORD')

    if not username:
        username = input("Enter your NameSilo username/email: ").strip()
    else:
        print(f"Using username from environment: {username[:5]}***")

    if not password:
        password = input("Enter your NameSilo password: ").strip()
    else:
        print("Using password from environment")

    if not username or not password:
        print("Error: Username and password are required!")
        sys.exit(1)

    # Retrieve API key
    api_key = get_namesilo_api_key(username, password)

    if api_key:
        print("\nSuccess! Your API key has been retrieved.")

        # Save to file
        api_file = "/root/namesilo_api_key.txt"
        with open(api_file, "w") as f:
            f.write(f"NameSilo API Key\n")
            f.write(f"{'='*60}\n")
            f.write(f"Username: {username}\n")
            f.write(f"API Key: {api_key}\n")
            f.write(f"{'='*60}\n")

        print(f"API key saved to: {api_file}")

        # Also save as environment variable format
        env_file = "/root/namesilo_api.env"
        with open(env_file, "w") as f:
            f.write(f"NAMESILO_API_KEY={api_key}\n")
            f.write(f"NAMESILO_USERNAME={username}\n")

        print(f"Environment variables saved to: {env_file}")
        print("\nYou can source this file with: source /root/namesilo_api.env")

    else:
        print("\nCould not automatically extract the API key.")
        print("Please check the screenshot and page source files in /root/")

if __name__ == "__main__":
    main()
