import os
import shutil
import time

from pathlib import Path

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager

from dotenv import load_dotenv
import mysql.connector
from mysql.connector import Error

load_dotenv()

GECKODRIVER_PATH = Path("/usr/local/bin/geckodriver")
FIREFOX_PROFILE_DIR = Path("/tmp")
FIREFOX_PROFILE_PREFIX = "rust_mozprofile"
STALE_PROFILE_MAX_AGE_SECONDS = 6 * 60 * 60


def _cleanup_stale_firefox_profiles(max_age_seconds=STALE_PROFILE_MAX_AGE_SECONDS):
    # Remove old geckodriver temp profiles so /tmp cannot grow forever.
    now = time.time()
    for profile_dir in FIREFOX_PROFILE_DIR.glob(f"{FIREFOX_PROFILE_PREFIX}*"):
        try:
            if not profile_dir.is_dir():
                continue
            if now - profile_dir.stat().st_mtime < max_age_seconds:
                continue
            shutil.rmtree(profile_dir, ignore_errors=True)
        except OSError:
            # Ignore cleanup issues and let the next run retry.
            continue


def _close_driver(driver):
    # quit() closes all windows and ends geckodriver cleanly.
    try:
        driver.quit()
    except Exception as error:
        print(f"driver.quit() failed: {error}")


def _create_driver():
    # Clean stale temporary profiles left behind by previous failed runs.
    _cleanup_stale_firefox_profiles()

    options = webdriver.FirefoxOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument("--window-size=1920,1200")
    options.binary_location = "/usr/bin/firefox"

    if GECKODRIVER_PATH.exists():
        service = FirefoxService(executable_path=str(GECKODRIVER_PATH))
    else:
        # Fallback keeps compatibility if an older image is missing geckodriver.
        service = FirefoxService(executable_path=GeckoDriverManager().install())

    return webdriver.Firefox(service=service, options=options)


def insert(evo100, evo95, evod, evodp):
    connection = None
    cursor = None
    try:
        connection = mysql.connector.connect(host=os.environ.get('DB_HOST'),
        user=os.environ.get('DB_USER'),
        passwd=os.environ.get('DB_PASSWORD'),
        db=os.environ.get('DB_NAME'))
        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute("insert into uzemanyag (EVO_100_benzin_plus, EVO_95_benzin, EVO_Diesel, EVO_Diesel_plus) values ('"+evo100+"','"+evo95+"','"+evod+"','"+evodp+"');")
            connection.commit()
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        # Close DB resources safely even when connect/cursor setup fails.
        if cursor is not None:
            cursor.close()
        if connection is not None and connection.is_connected():
            connection.close()

def check():
    driver = _create_driver()
    try:
        driver.get("https://b2bpartnerportal.com/")

        driver.find_element(By.ID, 'username').send_keys(os.environ.get('mol_user'))
        driver.find_element(By.ID, 'password').send_keys(os.environ.get('mol_pw'))
        driver.find_element(By.ID, 'login-button').click()

        driver.get('https://b2bpartnerportal.com/occ/#/dashboard')
        time.sleep(3)

        # menu baloldal
        driver.find_element(By.ID, 'menu-item-customer').click()
        time.sleep(3)

        # menu bal oldal reszlet
        driver.find_element(By.ID, 'menu-item-customer_detail').click()
        time.sleep(5)

        # ar lista lekredezes
        driver.find_element(By.ID, 'customer-details-pricing-method-list-prices-btn').click()
        time.sleep(5)

        # magyar halozat
        driver.find_element(By.ID, 'occ-select-multiple-networkCode-select-id').click()
        driver.find_elements(By.ID, 'occ-select-multiple-select-networkCode-select-id')[0].click()
        time.sleep(2)

        # uzemanyag tipusok
        driver.find_element(By.ID, 'occ-select-multiple-lpProductCode-select-id').click()
        driver.find_elements(By.ID, 'occ-select-multiple-select-lpProductCode-select-id')[7].click()
        driver.find_elements(By.ID, 'occ-select-multiple-select-lpProductCode-select-id')[8].click()
        driver.find_elements(By.ID, 'occ-select-multiple-select-lpProductCode-select-id')[9].click()
        driver.find_elements(By.ID, 'occ-select-multiple-select-lpProductCode-select-id')[10].click()
        time.sleep(1)

        driver.find_element(By.CLASS_NAME, 'occ-datepicker-button').click()
        time.sleep(1)
        driver.find_element(By.CLASS_NAME, 'selected').click()
        time.sleep(1)

        driver.save_screenshot('screenshot.png')

        time.sleep(2)
        driver.find_element(By.ID, 'buttonSearch').click()
        time.sleep(2)

        rows = driver.find_elements(By.CLASS_NAME, 'display-table-row')
        fuels = [0, 0, 0, 0]
        for row in rows:
            cells = row.find_elements(By.TAG_NAME, 'td')

            if "plus" in cells[5].text:
                if "benzin" in cells[5].text:
                    fuels[0] = cells[3].text
                    print(cells[3].text)
                if "Diesel" in cells[5].text:
                    fuels[3] = cells[3].text
                    print(cells[3].text)
            else:
                if "benzin" in cells[5].text:
                    fuels[1] = cells[3].text
                    print(cells[3].text)
                if "Diesel" in cells[5].text:
                    fuels[2] = cells[3].text
                    print(cells[3].text)

        insert(str(fuels[0]), str(fuels[1]), str(fuels[2]), str(fuels[3]))
    finally:
        _close_driver(driver)
        _cleanup_stale_firefox_profiles()
