import asyncio
import sys
from pathlib import Path
import traceback
import os
from dotenv import load_dotenv

# プロジェクトルートをパスに追加
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# .env を読み込む（例: プロジェクトルート直下）
load_dotenv(project_root / ".env")

from src.services.sync_service import SyncService
from src.services.notification_service import NotificationService
from src.services.pigeon_cloud_service import PigeonCloudService


# カスタム指示書
CUSTOM_INSTRUCTIONS = """
【指示書】
1.採用管理システムSonarにログイン
ログインURL
https://manager.snar.jp/agent.aspx
ID
info@career.cs-park.jp
パスワード
Kojikoji1007C

2.ジェイックの企業群が表示されているか確認
id="topBar"の中の企業名がジェイックになっていることを確認

3.推薦者管理ボタンをクリック(推薦者一覧を表示)

4.推薦者を最終更新日順にソート
id="ctl00_ctl00_cph_MstBody_cph_SubBody_wuc_AgentOBSListTable_tlv_List_sort_LastUpdateDate"を2回押して、直近変更が加えられたデータを表示

5.最終更新日が本日もしくは昨日で、ステータスが「予約」であり、ステップが説明会以外になってるユーザーを確認し、マイページに行き、予約日時を確認

6.該当情報が0件の場合のみ
「04_media-cs-notice」チャンネルに該当企業名、学生名、面接日時をSlack送付
"""

# Slack Webhook URL (.envから取得)
SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL_TO_CS_NOTICE")
PIGEON_CLOUD_JOB_ID = [825]
COMPANY_NAME = "株式会社ジェイック"

async def main():
    """メイン処理"""
    # 通知サービスの初期化
    notifier = NotificationService(slack_webhook_url=SLACK_WEBHOOK_URL)

    try:
        # 同期サービスのインスタンス作成
        sync_service = SyncService()
        pigeon_cloud_service = PigeonCloudService()

        # 面接データの取得と同期（カスタム指示書を渡し、MCPでPlaywrightの操作）
        result = await sync_service.sync_interview_data(
            instructions=CUSTOM_INSTRUCTIONS,
        )
        
        # MCP操作で獲得した、氏名、面接日時を元に、PigeonCloudの更新
        candidates = []
        if result:
            if hasattr(result, "candidates"):
                candidates = result.candidates
            elif isinstance(result, dict):
                candidates = result.get("candidates", [])

        for candidate in candidates:
            if hasattr(candidate, "full_name"):
                full_name = candidate.full_name
                interview_day = getattr(candidate, "interview_day", "")
                interview_start = getattr(candidate, "interview_start", "")
                interview_end = getattr(candidate, "interview_end", "")

                if interview_end:
                    print(interview_end)
                else:
                    print("interview_endは空だよ！")

                # update_interview_datesの返り値をチェック
                success = await pigeon_cloud_service.update_interview_dates(
                    PIGEON_CLOUD_JOB_ID,
                    full_name,
                    interview_day,
                    interview_start
                )

                # Falseの場合はSlack通知を送信
                if not success:
                    error_message = (
                        f"<!subteam^S089H0VBVFH>\n"
                        f"⚠️ PigeonCloud更新失敗\n"
                        f"企業名:{COMPANY_NAME}\n"
                        f"求人ID: {PIGEON_CLOUD_JOB_ID}\n"
                        f"氏名: {full_name}\n"
                        f"次回選考日程: {interview_day} {interview_start}\n"
                        f"理由: 該当エントリーが0件、または2件以上存在するため、次回選考日程を更新できませんでした。"
                    )
                    notifier.send_slack_message(error_message)
                    print(f"Slack通知送信: {full_name}のエントリーが0件または2件以上")

            else:
                continue
            
        # 結果を出力
        print(result)
        
    except Exception as e:
        # エラーメッセージとトレースバックを取得
        error_message = f"{str(e)}\n\n{traceback.format_exc()}"

        # Slackに通知
        script_name = Path(__file__).name
        notifier.send_slack_error(error_message, script_name)

        # コンソールにも出力
        print(f"エラーが発生しました: {error_message}")

        # エラーを再送出
        raise


if __name__ == "__main__":
    asyncio.run(main())
