"""Pigeon Cloud API クライアント"""
from __future__ import annotations
import os
from typing import Any, Dict, Optional
import requests

class PigeonCloudService:
    """Pigeon Cloud へのレコード検索と更新を扱うサービス"""

    def __init__(self, session: Optional[requests.Session] = None) -> None:
        self.session = session or requests.Session()
        self.api_url = os.getenv("PIGEON_CLOUD_API_URL")
        self.auth_token = os.getenv("PIGEON_CLOUD_AUTH_TOKEN")

    async def update_interview_dates(
        self,
        job_id: Optional[str],
        full_name: str,
        interview_day: str,
        interview_start: str,
    ) -> None:
        """求人IDと候補者リストを元に面接日程を更新"""
        if not job_id:
            print("PigeonCloudService: job_id が指定されていないためスキップします。")
            return False

        entry_data = self._get_job_entry_data(job_id, full_name)
        print(entry_data)
        single_entry = self._is_single_entry(entry_data)

        if not single_entry:
            
            return False
        
        #該当エントリーIDの取得
        entry_id = entry_data['data'][0]['raw_data']['id']
        
        #該当エントリーIDの次回選考日時の更新
        self._update_interview_date(entry_id, interview_day, interview_start)
        print("エントリーデータの更新が完了しました")
        return True
            

    def _headers(self) -> Dict[str, str]:
        """API ヘッダーを生成"""
        if self.auth_token:
            auth_token = self.auth_token
        else:
            print("AuthTokenが見つかりません")
        return {
            "x-pigeon-authorization": auth_token,
            "Content-Type": "application/json",
        }

    def _update_interview_date(self, entry_id: Any, interview_day: str, interview_start: str) -> None:
        """対象レコードの面接日程を更新"""
        payload = {
            "table": f"dataset__20",
            "data": [
                {
                    "id": entry_id,
                    "field__1177": f'{interview_day} {interview_start}',
                }
            ],
        }

        try:
            response = self.session.put(
                f"{self.api_url}/api/v1/record",
                json=payload,
                headers=self._headers(),
            )
            response.raise_for_status()
            
        except Exception as exc:  # pylint: disable=broad-except
            print(f"PigeonCloudService: 面接日程の更新に失敗しました (id={entry_id}) - {exc}")

    def _get_job_entry_data(self, job_id: Optional[str], full_name: str):
        """対象レコードの存在/個数を確認"""
        payload = {
        "table_id": "20",
        "condition":[
            {
                "and_or":"and",
                "field" : "field__766",
                "condition" : "eq",
                "value" : job_id
            },
            {
                "and_or":"and",
                "field" : "field__66",
                "condition" : "inc",
                "value" :full_name
            },
            {
                "and_or":"and",
                "field" : "field__918",
                "condition" : "eq",
                "value" :["2027卒","2028卒"]

            }
        ],
        "limit":2,
        }

        try:
            response = self.session.post(
                f"{self.api_url}/api/v1/get_record",
                json=payload,
                headers=self._headers(),
            )
            response.raise_for_status()
            
            return response.json()
            
        except Exception as exc:  # pylint: disable=broad-except
            print(f"PigeonCloudService:エントリーデータの取得に失敗しました (id={job_id}) - {exc}")

    def _is_single_entry(self, response_json: Dict[str, Any]) -> bool:
        """データの個数が1か、1以外(0or2以上)かをチェックし、エントリーデータが更新対象かを確認"""
        list_count = response_json["count"]
        
        if list_count == 1:
            return True
        
        print(f'名前重複、もしくは該当者なしでエントリーリストが0 or 2件以上発生しました')
        return False
        


    @staticmethod
    def _safe_json(response: requests.Response) -> Dict[str, Any]:
        """空レスポンスを考慮しつつ JSON を取り出す"""
        try:
            return response.json()
        except ValueError:
            return {}

if __name__ == "__main__":
    service = PigeonCloudService()
    # 例：環境変数や実値で埋める
    job_id = [830]
    full_name = "吉田太海"
    interview_day = "2025-10-15"
    interview_start = "14:00:00+09:00"

    service.update_interview_dates(job_id, full_name, interview_day, interview_start)
