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.common.exceptions import TimeoutException
import logging

from athenaidx.config import Config

class LoginPage:
    # 1. Locators (Use a clear naming convention)
    URL = "https://nsli-prod.rcm.athenahealth.com/rcm/#cfSystem=NSLI"
    USERNAME_INPUT = (By.ID, "username")
    PASSWORD_INPUT = (By.ID, "password")
    LOGIN_BUTTON = (By.ID, "pfh-login-module-button-login")
    
    def __init__(self, config: Config):
        self.driver = config.get_driver()
        config.set_logging_level(logging.DEBUG)
    
    def _navigate_to_login(self):
        self.driver.get(self.URL)

    def login(self, 
              username: str | None = None, 
              password: str | None = None):
        
        if username is None or password is None:
            username = input("Enter your username: ")
            password = input("Enter your password: ")
        
        if not username or not password:
            raise ValueError("Username and password must be provided")
        
        self._navigate_to_login()
        
        # Use an explicit wait to ensure the element is ready
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(self.USERNAME_INPUT)
        ).clear()
        self.driver.find_element(*self.USERNAME_INPUT).send_keys(username)
        
        self.driver.find_element(*self.PASSWORD_INPUT).clear()
        self.driver.find_element(*self.PASSWORD_INPUT).send_keys(password)
        self.driver.find_element(*self.LOGIN_BUTTON).click()

        try:
            error = WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((By.CSS_SELECTOR,"p.alert-block.error"))
            )
            error_text = error.text
            logging.error(f"Login error message: {error_text}")
            raise Exception("Login failed - invalid credentials")
        except TimeoutException:
            logging.info("Login successful - no error message detected")
            return True
    
