import sys
import logging
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
import os

# 現在のファイルのディレクトリパスを取得
current_dir = os.path.dirname(os.path.abspath(__file__))
# プロジェクトのsrcディレクトリパスを取得
src_path = os.path.abspath(os.path.join(current_dir, '..', 'src'))

sys.path.append(src_path)

from services.two_captcha import get_captcha_solution
import subprocess
from services.my_slack import send_slack_message, send_slack_submit_file
from utils.full_screen_shots import take_full_page_screenshot
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from utils.memory_logger import log_memory_usage
from config.load_env import load_environment_variables
import requests

#レイスグループへの自動エントリー(GoogleForm)
def race_auto_entry():
    import os
    import contextlib
    
    @contextlib.contextmanager
    def manage_xvfb():
        try:
            subprocess.run(['pkill', 'Xvfb'])
            xvfb_process = subprocess.Popen(['Xvfb', ':99', '-ac', '-screen', '0', '800x600x16'])
            os.environ['DISPLAY'] = ':99'
            yield
        finally:
            xvfb_process.terminate()
            xvfb_process.wait()
    
    @contextlib.contextmanager
    def manage_driver():
        driver = None
        try:
            options = Options()
            options.add_argument('--headless')
            options.add_argument('--no-sandbox')
            options.add_argument('--disable-gpu')
            options.add_argument('--window-size=1920,1080')
            options.add_argument('--disable-extensions')
            options.add_argument('--disk-cache-size=1')
            options.add_argument('--media-cache-size=1')
            
            service = Service(ChromeDriverManager().install())
            driver = webdriver.Chrome(service=service, options=options)
            yield driver
        finally:
            if driver:
                driver.quit()

    try:
        log_memory_usage("script_start")
        #環境変数の読み込み
        load_environment_variables()
        env = os.getenv("ENV")

        # ログファイル
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[logging.FileHandler("app.log")]
        )
        logger = logging.getLogger(__name__)

        #レイスグループの求人IDをここに記載
        unregistered_race_jobs = [
            {"id": 509, "name": "ビジネスタンク株式会社"},
            {"id": 499, "name": "レイスグループ総合職 2期"},
            {"id": 504, "name": "株式会社顧問名鑑"},
            {"id": 501, "name": "レイスシステムソリューションズ株式会社（RSS）"},
            {"id": 505, "name": "レイノス株式会社"},
            {"id": 503, "name": "mode株式会社"},
            {"id": 512, "name": "株式会社ロンザン"},
            {"id": 510, "name": "レイサス株式会社"},
            {"id": 513, "name": "リビジョン株式会社"},
            {"id": 508, "name": "レイナス株式会社"},
            {"id": 583, "name": "営業企画職／業務支援職"},
            {"id": 574, "name": "エムレイス株式会社"},
            {"id": 500, "name": "CS職（コーポレート部門）"},
            {"id": 502, "name": "レイテクソリューションズ株式会社"},
            {"id": 575, "name": "グレイスコミュニケーションズ株式会社"},
            {"id": 507, "name": "キー・ネットワーク株式会社／コミュニケーションデザイン株式会社"},
            {"id": 620, "name": "エイチ・オー・アイ・コンサルティング株式会社 2期"},
            {"id": 682, "name": "株式会社メディアタイムズ"}
        ]        
        
        #管理画面からエントリー対応が完了していない企業・該当学生の情報を取得
        for job in unregistered_race_jobs:
            unregisterd_race_job_id = job["id"]
            unregisterd_race_job_company_name = job["name"]
            print(unregisterd_race_job_company_name)

            unregisterd_race_entry_user_ids,unregisterd_race_entry_ids = get_unregisterd_race_entry_user_id(unregisterd_race_job_id)
            
            #未登録のエントリーの学生情報を、エントリー情報、会員情報の2視点から取得
            #for user_id, entry_id in zip(unregisterd_race_entry_user_ids, unregisterd_race_entry_ids):
                
            for unregisterd_race_entry_user_id,unregisterd_race_entry_id in zip(unregisterd_race_entry_user_ids, unregisterd_race_entry_ids):
                unregisterd_user_info = get_unregisterd_user_info(unregisterd_race_entry_user_id)
                unregisterd_user_entry_info = get_unregisterd_user_entry_info(unregisterd_race_entry_id)
                
                unregisterd_user_info["data"][0]["raw_data"]["field__47"]
                unregisterd_user_entry_info["data"][0]["raw_data"]["field__918"]
    
    
                #エントリーに必要な項目を定義
                company_name = unregisterd_race_job_company_name
                surname = unregisterd_user_info["data"][0]["raw_data"]["field__47"]
                given_name = unregisterd_user_info["data"][0]["raw_data"]["field__48"]
                surname_read = unregisterd_user_info["data"][0]["raw_data"]["field__68"]
                given_name_read = unregisterd_user_info["data"][0]["raw_data"]["field__69"]
                phone_number = unregisterd_user_info["data"][0]["raw_data"]["field__215"]
                mail_address = unregisterd_user_info["data"][0]["raw_data"]["field__216"]
                user_sex = unregisterd_user_info["data"][0]["raw_data"]["field__70"]
                birthday = unregisterd_user_info["data"][0]["raw_data"]["field__71"]
                user_prefecture = unregisterd_user_info["data"][0]["raw_data"]["field__210"]
                user_university = unregisterd_user_info["data"][0]["view_data"]["field__73"]
                user_department = unregisterd_user_info["data"][0]["raw_data"]["field__74"]
                graduate_year = unregisterd_user_info["data"][0]["raw_data"]["field__207"]
                graduate_month = "3月"
                entry_date_time = unregisterd_user_entry_info["data"][0]["raw_data"]["field__689"]

                print(f'''会社名：{company_name}
{surname}さんのデータ取得中
''')
                row_count = 1  # 1から開始するカウンタ,スプレッドシートのエントリー文字列を変更するために利用
                row_count += 1
                print(row_count)


                with manage_xvfb(), manage_driver() as driver:
                    log_memory_usage("driver_initialized")

                    driver.get("https://docs.google.com/forms/d/e/1FAIpQLSeOvjLQwmE1K8RYqsr_9y6oiQacDBvW3-3_qz90txplOjUb0A/viewform")

                    # 少し待つ（ページが完全に読み込まれるまで待機）
                    time.sleep(3)
                    
                    #メアド入力
                    email_address = "info@career.cs-park.jp"
                    script = f'''
                    var emailField = document.querySelector('input[type="email"]');
                    if (emailField) {{
                        Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(emailField, "{email_address}");
                        emailField.dispatchEvent(new Event('input', {{ bubbles: true }}));
                    }}
                    '''
                    driver.execute_script(script)

                    #会社名入力
                    company_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    company_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, company_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    mycompany = "株式会社CSParkCareer"
                    driver.execute_script(script, company_field, mycompany)
                    
                    #記入者入力
                    writer_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[3]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    writer_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, writer_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    writer = "中島幸司"
                    driver.execute_script(script, writer_field, writer)
                    
                    #記入者携帯番号
                    writer_phone_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[4]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    writer_phone_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, writer_phone_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    writer_phone = '080-5409-5238'
                    driver.execute_script(script, writer_phone_field, writer_phone)
                    
                    #ユーザー姓
                    user_surname_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[5]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    user_surname_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, user_surname_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, user_surname_field, surname)

                    #ユーザー名
                    user_givenname_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[6]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    user_givenname_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, user_givenname_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, user_givenname_field, given_name)

                    #ユーザーセイ
                    surname_read_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[7]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    surname_read_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, surname_read_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, surname_read_field, surname_read)
                    
                    #ユーザーメイ
                    given_name_read_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[8]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    given_name_read_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, given_name_read_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, given_name_read_field, given_name_read)

                    #携帯番号
                    phone_number_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[9]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    phone_number_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, phone_number_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, phone_number_field, phone_number)
                        
                    #メアド
                    mail_address_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[10]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    mail_address_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, mail_address_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    #driver.execute_script(script, mail_address_field, mail_address)
                    driver.execute_script(script, mail_address_field, mail_address)
                    #性別【選択式】値表示
                    driver.find_element(By.CLASS_NAME, 'ry3kXd').click()
                    
                    #性別【選択式】値クリック
                    if user_sex == "男性":
                        user_sex_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[12]/div/div/div[2]/div/div[2]/div[3]/span'
                        user_sex_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, user_sex_xpath)))
                        user_sex_field.click()
                    else:
                        user_sex_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[12]/div/div/div[2]/div/div[2]/div[4]/span'
                        user_sex_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, user_sex_xpath)))
                        user_sex_field.click()
                    try:
                        option = WebDriverWait(driver, 10).until(
                            EC.element_to_be_clickable((By.CSS_SELECTOR, f"[data-value='{user_sex}']"))
                        )
                        option.click()
                        print(f"性別クリック成功")
                        #return True  # 選択成功
                    except Exception as e:
                            print(f"Error selecting option '{user_sex}': {e}")
                            #return False # 選択失敗
                            import traceback
                            traceback.print_exc()  # スタックトレースを出力
                            return False # 選択失敗
                    #空クリック
                    driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]').click()

                    #生年月日           
                    WebDriverWait(driver, 10).until(
                        EC.presence_of_element_located((By.XPATH, '//*[@id="mG61Hd"]'))
                    )
                    
                    date_input_xpath = '//input[@type="date" and @class="whsOnd zHQkBf"]'
                    wait = WebDriverWait(driver, 10)
                    date_input = wait.until(EC.presence_of_element_located((By.XPATH, date_input_xpath)))
                    
                    date_obj = datetime.strptime(birthday, "%Y-%m-%d")
                    new_date_value = date_obj.strftime("%Y-%m-%d")
                    
                    script = """
                    var dateInput = arguments[0];
                    var newDateValue = arguments[1];
                    dateInput.setAttribute('data-initial-value', newDateValue);
                    dateInput.value = newDateValue;
                    var event = new Event('input', { bubbles: true });
                    dateInput.dispatchEvent(event);
                    """
                    driver.execute_script(script, date_input, new_date_value) 
                    
                    #空クリック
                    driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]').click()
                    wait = WebDriverWait(driver, 5)
                    # 住所【選択式】都道府県の選択
                    def normalize_prefecture(pref_name):
                        # 全角スペースを半角に変換し、前後の空白を削除
                        pref_name = pref_name.replace('　', ' ').strip()
                        # 都道府県を削除
                        pref_name = pref_name.replace('都', '').replace('道', '').replace('府', '').replace('県', '')
                        return pref_name


                    prefecture_dropdown = WebDriverWait(driver, 10).until(
                        EC.element_to_be_clickable((By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[14]/div/div/div[2]/div'))
                    )
                    # ドロップダウンをクリック
                    driver.execute_script("arguments[0].click();", prefecture_dropdown)
                    
                    # 都道府県名を正規化
                    modified_prefecture = normalize_prefecture(user_prefecture)
                    print(modified_prefecture)
                    try:
                            # ドロップダウンをクリック
                        prefecture_dropdown = WebDriverWait(driver, 10).until(
                            EC.element_to_be_clickable((By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[14]/div/div/div[2]/div/div[1]/div[1]'))
                        )
                        prefecture_dropdown.click()
                        time.sleep(2)
                        # EC.element_to_be_clickable((By.CSS_SELECTOR, f'[data-value="{modified_prefecture}"]'))
                            #EC.element_to_be_clickable((By.CSS_SELECTOR, f"[data-value='{u           ser_sex}']"))
                        # )
                        #option.click()
                        print(f"県選択成功")
                        #return True  # 選択成功
                    except Exception as e:
                        print(f"Error selecting option '{modified_prefecture}': {type(e)}") # 例外の型を出力
                        import traceback
                        traceback.print_exc()  # スタックトレースを出力
                        return False # 選択失敗
                        
                        # 改善されたJavaScript
                    try:
                        select_prefecture_js = f"""
                        function selectPrefecture() {{
                            return new Promise((resolve) => {{
                                var targetPref = "{modified_prefecture}";
                                var maxAttempts = 5;
                                var currentAttempt = 0;
                                
                                function attemptSelection() {{
                                    var options = Array.from(document.querySelectorAll('div[role="option"]'));
                                    
                                    for (let option of options) {{
                                        let text = option.innerText || option.textContent;
                                        let cleanText = text.replace(/[都道府県]/g, '').trim();
                                        console.log(cleanText, targetPref); 
                                        if (cleanText === targetPref) {{
                                            option.scrollIntoView({{behavior: 'instant', block: 'center'}});
                                            
                                            setTimeout(() => {{
                                                try {{
                                                    var clickEvent = new MouseEvent('click', {{
                                                        bubbles: true,
                                                        cancelable: true,
                                                        view: window
                                                    }});
                                                    option.dispatchEvent(clickEvent);
                                                    resolve(true);
                                                }} catch (e) {{
                                                    console.error('クリックエラー:', e);
                                                    resolve(false);
                                                }}
                                            }}, 500);
                                            
                                            return;
                                        }}
                                    }}
                                    
                                    currentAttempt++;
                                    if (currentAttempt < maxAttempts) {{
                                        setTimeout(attemptSelection, 1000);
                                    }} else {{
                                        resolve(false);
                                    }}
                                }}
                                
                                attemptSelection();
                            }});
                        }}
                        return selectPrefecture();
                        """
                        
                        # JavaScriptの実行を待機
                        selection_successful = driver.execute_script(select_prefecture_js)
                        # 選択が成功したか確認
                        if not selection_successful:
                            raise Exception(f"都道府県 '{modified_prefecture}' の選択に失敗しました")
                        
                        # 選択後、少し待機して確実に反映されるようにする
                        time.sleep(1)
                        
                    except Exception as e:
                        logger.error(f"都道府県選択でエラー: {str(e)}")
                        raise e

                    #空クリック
                    driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]').click()
                    
                    #学校名
                    user_university_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[15]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    user_university_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, user_university_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, user_university_field, user_university)
                    
                    #学部学科
                    user_department_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[16]/div/div/div[2]/div/div[1]/div/div[1]/input'
                    user_department_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, user_department_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, user_department_field, user_department)
                    
                    #卒業年
                    driver.find_element(By.XPATH, '//*[@id="i91"]/div[3]/div').click()
                    
                    #空クリック
                    driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]').click()
                    
                    #予約先会社名
                    #driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[19]/div/div/div[2]/div/div[1]/div[1]/div[1]/span').click()
                    js_code = """
                    document.evaluate(
                        '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[19]/div/div/div[2]/div/div[1]',
                        document,
                        null,
                        XPathResult.FIRST_ORDERED_NODE_TYPE,
                        null
                    ).singleNodeValue.click();

                    """
                    try:
                        # ドロップダウンをクリック
                        company_dropdown = WebDriverWait(driver, 10).until(
                            EC.element_to_be_clickable((By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[19]/div/div/div[2]/div/div[1]/div[1]'))
                        )
                        company_dropdown.click()
                        time.sleep(2)
                        # 選択要素をクリック
                        select_company_js = f"""
                        function selectPrefecture() {{
                            return new Promise((resolve) => {{
                                var targetText = "{company_name}";
                                var maxAttempts = 5;
                                var currentAttempt = 0;
                                
                                function attemptSelection() {{
                                    var options = Array.from(document.querySelectorAll('div[role="option"]'));
                                    
                                    for (let option of options) {{
                                        let text = option.innerText || option.textContent;
                                        if (text === targetText) {{
                                            option.scrollIntoView({{behavior: 'instant', block: 'center'}});
                                            setTimeout(() => {{
                                                try {{
                                                    var clickEvent = new MouseEvent('click', {{
                                                        bubbles: true,
                                                        cancelable: true,
                                                        view: window
                                                    }});
                                                    option.dispatchEvent(clickEvent);
                                                    resolve(true);
                                                }} catch (e) {{
                                                    console.error('クリックエラー:', e);
                                                    resolve(false);
                                                }}
                                            }}, 500);
                                            return;
                                        }}
                                    }}
                                    
                                    currentAttempt++;
                                    if (currentAttempt < maxAttempts) {{
                                        setTimeout(attemptSelection, 1000);
                                    }} else {{
                                        resolve(false);
                                    }}
                                }}
                                
                                attemptSelection();
                            }});
                        }}
                        return selectPrefecture();
                        """
                        # JavaScriptの実行を待機
                        selection_successful = driver.execute_script(select_company_js)
                        print(selection_successful)
                        # 選択が成功したか確認
                        if not selection_successful:
                            raise Exception(f"都道府県 '{modified_prefecture}' の選択に失敗しました")

                            # 選択後、少し待機して確実に反映されるようにする
                        time.sleep(1)
                        #driver.execute_script(js_code)
                                                
                        print(f"企業名:"+company_name)
                        print(f"企業名選択成功")
                        #return True  # 選択成功
                    except Exception as e:
                        print(f"Error selecting option '{company_name}': {type(e)}") # 例外の型を出力
                        import traceback
                        traceback.print_exc()  # スタックトレースを出力
                        return False # 選択失敗

                    #空クリック
                    driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]').click()
                    # エントリー予定日時
                    event_date_input_xpath = ('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[20]/div/div/div[2]/div/div[1]/div[2]/div[1]/div/div[1]/input')
                    wait = WebDriverWait(driver, 10)
                    event_date_input = wait.until(EC.presence_of_element_located((By.XPATH, event_date_input_xpath)))
                    print(f"エントリー予定日時")
                    print(entry_date_time)
                    date_part = entry_date_time.split(' ')[0]
                    print(date_part)
                    #formatted_event_date = datetime.strptime(date_part, "%Y/%m/%d").strftime("%Y-%m-%d")

                    event_date_script = """
                    var dateInput = arguments[0];
                    var newDateValue = arguments[1];
                    dateInput.setAttribute('data-initial-value', newDateValue);
                    dateInput.value = newDateValue;
                    var event = new Event('input', { bubbles: true });
                    dateInput.dispatchEvent(event);
                    """
                    driver.execute_script(event_date_script, event_date_input, date_part)
                                    
                    #エントリー予定時間
                    time_range = entry_date_time.split(' ')[1]
                    start_time = time_range.split('-')[0]
                    start_hour, start_minute = start_time.split(':')

                    #開始時間 入力
                    entry_hour_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[20]/div/div/div[2]/div/div[2]/div/div/div[1]/div[2]/div[1]/div/div[1]/input'
                    entry_hour_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, entry_hour_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """
                    driver.execute_script(script, entry_hour_field, start_hour)

                    #開始分 入力
                    entry_minute_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[20]/div/div/div[2]/div/div[2]/div/div/div[3]/div/div[1]/div/div[1]/input'
                    entry_minute_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, entry_minute_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    start_time = time_range.split('-')[0]
                    start_hour, start_minute = start_time.split(':')
                    """
                    #開始時間 入力
                    entry_hour_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[20]/div/div/div[2]/div/div[2]/div/div/div[1]/div[2]/div[1]/div/div[1]/input'
                    entry_hour_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, entry_hour_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """

                    driver.execute_script(script, entry_hour_field, start_hour)

                    #開始分 入力
                    entry_minute_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[20]/div/div/div[2]/div/div[2]/div/div/div[3]/div/div[1]/div/div[1]/input'
                    entry_minute_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, entry_minute_xpath)))
                    script = """
                    arguments[0].value = arguments[1];
                    var event = new Event('input', { bubbles: true });
                    arguments[0].dispatchEvent(event);
                    """ 
                    driver.execute_script(script, entry_minute_field, start_minute)
                    

                    #空クリック
                    driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]').click()
                    
                    #説明会予定日までの日数クリック
                    radio_button_xpath = '//*[@id="i118"]/div[3]/div'
                    radio_button = WebDriverWait(driver, 10).until(
                        EC.element_to_be_clickable((By.XPATH, radio_button_xpath))
                    )
                    radio_button.click()
                    
                    #空クリック
                    driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]').click()
                    
                    if env == "staging":
                        screenshot_path = '/var/www/html/status_management/staging/file/screen_shot'
                    elif env == "production":
                        screenshot_path = '/var/www/html/status_management/src/file/screen_shot'
                        
                    now = datetime.now()
                    formatted_date = now.strftime('%Y%m%d%H%M')
                    screenshot_file_name = f"{company_name}_{surname}{given_name}_{formatted_date}.png"

                    try:
                        take_full_page_screenshot(driver, screenshot_path, screenshot_file_name)

                        #送信ボタンを押す前に、recapthcaトークンをDOMに挿入
                        captcha_solution = get_captcha_solution()
                        driver.execute_script(f'document.getElementById("g-recaptcha-response").value="{captcha_solution}";')
                        time.sleep(2)
                                        
                        #送信ボタンクリック
                        submit_button_xpath = '//*[@id="mG61Hd"]/div[2]/div/div[3]/div[3]/div[1]/div/span/span'
                        submit_button = WebDriverWait(driver, 10).until(
                            EC.element_to_be_clickable((By.XPATH, submit_button_xpath))
                        )
                        submit_button.click()
                        
                        time.sleep(2)
                        
                        file_name = f"{company_name}_{surname}{given_name}_{formatted_date}_submit.png"
                        take_full_page_screenshot(driver, screenshot_path, file_name)
                        log_memory_usage("screenshot_taken", f"{surname}{given_name}")
                        
                        send_slack_submit_file(company_name,surname,given_name,formatted_date)
                        
                        #Slackに通知
                        username = surname + given_name
                        message = f"<!subteam^S08AB4JUL92>{username}さん\n{company_name}へのエントリーが完了しました。"
                        send_slack_message(message, "WEBHOOK_URL_CS_NOTICE")
                        
                        # #スプレッドシートの中身をエントリー→本日日時に変更
                        # today = datetime.now()
                        # formatted_date = today.strftime('%Y/%m/%d(%a)')
                        
                        # cell_row = row_count
                        # cell_col = 33 #AG列(入力データ)を変更
                        # new_value = formatted_date
                        # sheet_entry_info.update_cell(cell_row, cell_col, new_value)
                        log_memory_usage("form_submitted", f"{surname}{given_name}")
                        change_race_entry_status(unregisterd_race_entry_id)

                    except Exception as e:
                        logger.error(f"ブラウザ操作エラー: {str(e)}")
                        log_memory_usage("error_occurred", f"{surname}{given_name}")
                        error_message = f"<!subteam^S08AB4JUL92>RPAエラーが発生しました。\nエラー内容: {str(e)}"
                        send_slack_message(error_message, "WEBHOOK_URL_CS_NOTICE")
                        raise

    except Exception as e:
        logger.error(f"予期せぬエラー: {str(e)}")
        error_message = f"<!subteam^S08AB4JUL92>RPAエラーが発生しました。\nエラー内容: {str(e)}"
        send_slack_message(error_message, "WEBHOOK_URL_CS_NOTICE")
    finally:
        if 'driver' in locals() and driver is not None:
            try:
                driver.quit()
                log_memory_usage("script_end")
            except Exception as e:
                logger.error(f"ドライバー終了エラー: {str(e)}")
        


#管理画面からエントリー対応が完了していない企業・該当学生の情報を取得
def get_api_credentials():
    PIGEON_API = os.getenv("PIGEON_API")
    if not PIGEON_API:
        raise ValueError("PIGEON_API environment variable is not set")

    API_KEY = os.getenv("API_KEY")
    if not API_KEY:
        raise ValueError("API_KEY environment variable is not set")
        
    return PIGEON_API, API_KEY

#レイスグループで、ステータスが予約中のものの会員IDを取得
def get_unregisterd_race_entry_user_id(job_id):
    
    PIGEON_API, api_key = get_api_credentials()
    api_url = f'https://{PIGEON_API}/api/v1/get_record'

    json_body = {
        "table_id": "20",
        "condition":[
            {
                "and_or":"and",
                "field" : "field__766",
                "condition" : "eq",
                "value" : job_id
            },
            {
                "and_or":"and",
                "field" : "field__343",
                "condition" : "eq",
                "value" : "9" #ステータスが「予約中」
            },
            {
                "and_or":"and",
                "field" : "field__918",
                "condition" : "eq",
                "value" : "2026卒" #ターゲット年度が「2026卒」
            }
        ]
        }

    # Headers for the request
    headers = {
        'x-pigeon-authorization': api_key,
        'Content-Type': 'application/json'
    }

    # Making the POST request
    response = requests.post(api_url, json=json_body, headers=headers)

    # Checking if the request was successful
    if response.status_code == 200:
        race_entry_user_id_values = [entry["raw_data"]["field__761"] for entry in response.json()["data"]]
        race_entry_id_values = [entry["raw_data"]["id"] for entry in response.json()["data"]]
        print(race_entry_user_id_values)
        print(race_entry_id_values)
        
        return race_entry_user_id_values,race_entry_id_values
    else:
        # If unsuccessful, print out the status code and response text
        print(f'Failed to get records: {response.status_code}')
        print(response.text)
  
def change_race_entry_status(entry_id):
    PIGEON_API, api_key = get_api_credentials()
    api_url = f'https://{PIGEON_API}/api/v1/record'

    json_body = {
                    "table": "dataset__20",
                    "data": [
                        {
                            "id":entry_id,
                            "field__343": "20"
                        }
                    ]
                }

    # Headers for the request
    headers = {
        'x-pigeon-authorization': api_key,
        'Content-Type': 'application/json'
    }

    # Making the POST request
    response = requests.put(api_url, json=json_body, headers=headers)

    # Checking if the request was successful
    if response.status_code == 200:
        return response.json()
    else:
        # If unsuccessful, print out the status code and response text
        print(f'Failed to get records: {response.status_code}')
        print(response.text)

#レイスグループへ未登録ユーザーのユーザー情報を取得
def get_unregisterd_user_info(user_id):
    PIGEON_API, api_key = get_api_credentials()
    api_url = f'https://{PIGEON_API}/api/v1/get_record'

    json_body = {
        "table_id": "12",
        "condition":[
            {
                "and_or":"and",
                "field" : "id",
                "condition" : "eq",
                "value" : user_id
            }
        ],
        }

    # Headers for the request
    headers = {
        'x-pigeon-authorization': api_key,
        'Content-Type': 'application/json'
    }

    # Making the POST request
    response = requests.post(api_url, json=json_body, headers=headers)

    # Checking if the request was successful
    if response.status_code == 200:
        response_data = response.json()
        return response_data
    else:
        # If unsuccessful, print out the status code and response text
        print(f'Failed to get records: {response.status_code}')
        print(response.text)

#レイスグループへ未登録ユーザーのレイスエントリー情報を取得
def get_unregisterd_user_entry_info(entry_id):
    PIGEON_API, api_key = get_api_credentials()
    api_url = f'https://{PIGEON_API}/api/v1/get_record'

    #取得できたデータの個数が1個の場合はアップデート、それ以外の場合は、スラッくに通知などで対応？
    json_body = {
        "table_id": "20",
        "condition":[
            {
                "and_or":"and",
                "field" : "id",
                "condition" : "eq",
                "value" : entry_id
            }
        ],
        }

    # Headers for the request
    headers = {
        'x-pigeon-authorization': api_key,
        'Content-Type': 'application/json'
    }

    # Making the POST request
    response = requests.post(api_url, json=json_body, headers=headers)

    # Checking if the request was successful
    if response.status_code == 200:
        response_data = response.json()
        #print(response_data)
        return response_data
    else:
        # If unsuccessful, print out the status code and response text
        print(f'Failed to get records: {response.status_code}')
        print(response.text)
    

if __name__ == "__main__":
    race_auto_entry()