import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager


def fetch_results(hall_tickets):

    if not isinstance(hall_tickets, list):
        raise ValueError("hall_tickets must be a list")

    options = Options()
    options.add_argument("--headless=new")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")

    driver = webdriver.Chrome(
        service=Service(ChromeDriverManager().install()),
        options=options
    )

    wait = WebDriverWait(driver, 10)

    url = "https://results.cmrithyderabad.edu.in/result/13d6580997ee69af855718b5eb0d861d"
    driver.get(url)

    input_box = wait.until(
        EC.presence_of_element_located((By.CLASS_NAME, "hallticket"))
    )
    button = driver.find_element(By.CLASS_NAME, "getResultButton")

    all_students = []

    for ht in hall_tickets:
        try:
            input_box.clear()
            input_box.send_keys(ht)

            driver.execute_script("arguments[0].click();", button)

            wait.until(
                lambda d: len(d.find_elements(By.CLASS_NAME, "table")) >= 2
            )

            student_data = {"Hall Ticket": ht}

            tables = driver.find_elements(By.CLASS_NAME, "table")

            detail_cells = tables[0].find_elements(By.CLASS_NAME, "row")[1] \
                .find_elements(By.CLASS_NAME, "cell")

            student_data["Name"] = detail_cells[1].text
            student_data["Branch"] = detail_cells[2].text
            student_data["Credits"] = detail_cells[3].text
            student_data["SGPA"] = detail_cells[4].text
            student_data["Status"] = detail_cells[5].text

            subject_rows = tables[1].find_elements(By.CLASS_NAME, "row")[1:]

            for row in subject_rows:
                cells = row.find_elements(By.CLASS_NAME, "cell")
                subject_name = cells[1].text
                grade_point = cells[3].text
                student_data[subject_name] = grade_point

            all_students.append(student_data)

            driver.execute_script(
                "document.getElementsByClassName('wrapper')[0].innerHTML='';"
            )

        except:
            continue

    driver.quit()

    return pd.DataFrame(all_students)