from dotenv import load_dotenv
import time
import os

from selenium import webdriver
from browsermobproxy import Server

from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

from z_zerodha_totp import get_totp
from z_get_websocket import get_data

# Load the .env file
load_dotenv()
username = os.getenv("ZERODHA_USERNAME")
password = os.getenv("ZERODHA_PASSWORD")

# Define paths and URLs as constants
BROWSERMOB_PROXY_PATH = "C:\\browsermob-proxy-2.1.4\\bin\\browsermob-proxy"
CHROMEDRIVER_PATH = "C:/chromedriver.exe"
Zerodha_URL = "https://kite.zerodha.com/"

def verify_auth():
    # Start the BrowserMob Proxy Server
    server = Server(BROWSERMOB_PROXY_PATH, options={'port': 8090})
    server.start()
    proxy = server.create_proxy(params={"trustAllServers": "true"})

    # Configure Chrome options
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--disable-web-security")
    chrome_options.add_argument("--ignore-certificate-errors")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("--headless")  # Run in headless mode to avoid UI issues
    chrome_options.add_argument(f"--proxy-server={proxy.proxy}")

    # Initialize Chrome WebDriver
    service = Service(executable_path=CHROMEDRIVER_PATH)
    driver = webdriver.Chrome(service=service, options=chrome_options, keep_alive=True)

    try:
        # Create a new HAR file for capturing network traffic from the specified Zerodha URL
        proxy.new_har(Zerodha_URL)

        # Request the web page from "Zerodha_URL"
        driver.get(Zerodha_URL)  # Login Page
        time.sleep(10)

        # Re-request the web page to simulate human behavior
        driver.get(Zerodha_URL)  # Reload Login Page
        driver.get(Zerodha_URL)  # Reload Login Page
        driver.get(Zerodha_URL)  # Reload Login Page

        # Enter login credentials
        driver.find_element(By.ID, 'userid').send_keys(username)
        driver.find_element(By.ID, 'password').send_keys(password)
        driver.find_element(By.XPATH, "//button").click()
        time.sleep(5)

        # Enter TOTP
        totp = get_totp()
        driver.find_element(By.XPATH, "//input[@label='External TOTP']").send_keys(totp)
        time.sleep(30)

        driver.get(Zerodha_URL)  # Reload Login Page
        driver.get(Zerodha_URL)  # Reload Login Page
        driver.get(Zerodha_URL)  # Reload Login Page

        # Extract data
        filtered_data = get_data(har_parser_data=proxy.har)

    finally:
        # Clean up resources
        driver.quit()
        server.stop()

    return filtered_data