import os
import sys
import time
from datetime import datetime
from dotenv import load_dotenv
import gspread
from google.oauth2.service_account import Credentials

from services.my_slack import send_slack_message
from services.pigeon_cloud import PigeonCloud
from config.load_env import load_environment_variables

#.env.staging or .env.productionのいずれかから環境変数の取得
load_environment_variables()

def schedule_change():
    # PigeonCloudインスタンスを作成
    pigeon = PigeonCloud()
    # 認証情報のパス
    PROD_SERVICE_ACCOUNT_FILE = os.getenv('PROD_SERVICE_ACCOUNT_FILE')
    # スコープの定義
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
    # 認証情報を読み込む
    creds = Credentials.from_service_account_file(PROD_SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    # クライアントの作成
    client = gspread.authorize(creds)

    #日程変更RPAのシートID取得
    SCHEDULE_CHANGE_SPREADSHEET_ID = os.getenv("SCHEDULE_CHANGE_SPREADSHEET_ID")
    RANGE_NAME = 'A3:O3000'  # 取得したい範囲を指定

    # スプレッドシートの取得
    sheet = client.open_by_key(SCHEDULE_CHANGE_SPREADSHEET_ID)
    # シートの選択
    worksheet = sheet.worksheet('【RPA】日程追加')
    # 値の取得
    schedule_values = worksheet.get(RANGE_NAME)

    filtered_values = [row for row in schedule_values if row[0].strip()]

    row_count = 2  # 1から開始するカウンタ,スプレッドシートのエントリー文字列を変更するために利用
    # 取得した値の表示
    for company_value in filtered_values:
            
            row_count += 1
            
            job_id = company_value[0]
            orientation_day = company_value[2]
            start_time = company_value[3]
            end_time = company_value[4]
            location = company_value[5]
            max_capacity = company_value[6]
            deadline = company_value[7]
            new_task = company_value[8]
            register_check = company_value[11]
            

            # E列（4番目の値）が存在するか確認し、存在しない場合はデフォルト値を設定
            if not register_check:
                pigeon.add_orientation_date(job_id, orientation_day, start_time, end_time, location, max_capacity, deadline, new_task)
                
                #入力した日付をセルに入力
                today = datetime.now()
                formatted_date = today.strftime('%Y/%m/%d')
                
                cell_row = row_count
                cell_col = 12 #AG列(登録完了)を変更
                new_value = formatted_date
                worksheet.update_cell(cell_row, cell_col, new_value)
                print(f"{row_count}列 掲載完了")
                # 2秒待つ API制限対応
                time.sleep(2)
            
            else:
                print(f"{row_count}列 掲載済み日程")
                continue

                    
    #入力が終了したSlack通知                            
    message =  "日程掲載が完了しました。"
    webhook_url = os.getenv("WEBHOOK_URL_CS_NOTICE")
    send_slack_message(message, webhook_url)

if __name__ == "__main__":
    schedule_change()
