import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from config.load_env import load_environment_variables
load_environment_variables()
from workflows.schedule_change import schedule_change
from config.app_config import app_config
from fastapi import FastAPI
from fastapi.security import HTTPBasic
import logging
import subprocess
from concurrent.futures import ThreadPoolExecutor


app = FastAPI(docs_url="/docs", redoc_url="/redoc")
security = HTTPBasic()
current_directory = os.path.dirname(os.path.abspath(__file__))


# スレッドプールの設定
executor = ThreadPoolExecutor(max_workers=3)

#ログ出力の設定
logging.basicConfig(
    filename=f'{current_directory}/error.log',  # 出力先ファイル
    level=logging.ERROR,  # ログレベル
    format='%(asctime)s - %(levelname)s - %(message)s'
)

# app.logファイル用のロガーを事前設定
app_logger = logging.getLogger('app')
app_logger.setLevel(logging.INFO)
app_log_handler = logging.FileHandler(f'{current_directory}/app.log')
app_log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app_log_handler.setFormatter(app_log_formatter)
if not app_logger.handlers:  # 重複を避ける
    app_logger.addHandler(app_log_handler)

#app.pyの起動確認用
@app.get("/")
def root():
  return {"message": "Hello, World!正しく起動。StatusManagement!!!"}

@app.get("/schedule_change/")
def schedule_change_endpoint():
    app_logger.info("schedule_change endpoint called")
    
    try:
        app_logger.info("Starting schedule_change function execution")
        schedule_change()
        app_logger.info("schedule_change function completed successfully")
        return "新規日程掲載実行中(2~3分程でSlackに実行完了通知が行きます)"
        
    except Exception as e:
        import traceback
        error_traceback = traceback.format_exc()
        app_logger.error(f"Exception occurred in schedule_change: {str(e)}")
        app_logger.error(f"Exception type: {type(e).__name__}")
        app_logger.error(f"Full traceback: {error_traceback}")
        return {"error": f"新規日程掲載中にエラーが発生しました: {str(e)}"}

@app.get("/management_status/")
def management_status_endpoint():

    python_path = sys.executable
    script_path = os.path.join(os.path.dirname(current_directory), "scripts", "run_grad26_progress_individual.py")
    
    # 設定ファイルから環境変数を取得
    env = app_config.get_subprocess_env()

    try:
        # subprocessで外部Pythonスクリプトを実行
        subprocess.run(
            [python_path, script_path],  # 引数なしで実行
            capture_output=True,
            text=True,
            env=env
        )
        
        return "26卒用個別進捗管理が回りました。Slackの完了通知を確認してください。"

    except Exception as e:
        return {"error": f"スクリプト実行中にエラーが発生しました: {str(e)}"}  
      

@app.get("/grad27_management_status/")
def grad27_management_status_endpoint():

    # ログの設定
    logger = logging.getLogger('status_management')
    logger.setLevel(logging.INFO)
    
    # app.logファイルハンドラがまだない場合は追加
    app_log_path = f'{current_directory}/app.log'
    file_handler = logging.FileHandler(app_log_path)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    
    # 既存のハンドラを確認して重複を避ける
    if not any(isinstance(handler, logging.FileHandler) and handler.baseFilename == os.path.abspath(app_log_path) for handler in logger.handlers):
        logger.addHandler(file_handler)
    
    logger.info("grad27_management_status endpoint called")
    
    python_path = sys.executable
    script_path = os.path.join(os.path.dirname(current_directory), "scripts", "run_grad27_progress_individual.py")
    
    # 設定ファイルから環境変数を取得
    env = app_config.get_subprocess_env()

    try:
        logger.info(f"Executing script: {script_path}")
        # subprocessで外部Pythonスクリプトを実行
        result = subprocess.run(
            [python_path, script_path],  # 引数なしで実行
            capture_output=True,
            text=True,
            env=env
        )
        
        if result.returncode == 0:
            logger.info("Script executed successfully")
        else:
            logger.error(f"Script failed with return code: {result.returncode}")
            logger.error(f"stderr: {result.stderr}")
        
        return "27卒用個別進捗管理が回りました。Slackの完了通知を確認してください。"

    except Exception as e:
        logger.error(f"Exception occurred while executing script: {str(e)}")
        return {"error": f"スクリプト実行中にエラーが発生しました: {str(e)}"}  

if __name__ == '__main__':
  import uvicorn
  uvicorn.run(app, host="0.0.0.0", port=9000)
