import json
import requests
from flask import Flask, request, jsonify, current_app
from google.oauth2 import service_account
from google.auth.transport.requests import Request
import logging

# Flask 앱 설정
app = Flask(__name__)
app.config['FCM_PROJECT_ID'] = 'plantra-3dcb4'  # Firebase 프로젝트 ID

# 로거 설정
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class FCM:
    @classmethod
    def get_access_token(cls) -> str:
        """OAuth2 액세스 토큰 생성"""
        # JSON 파일 내용 하드코딩 (보안을 위해 환경변수나 안전한 저장소에 저장 권장)
        service_account_info = {
             "type": "service_account",
              "project_id": "plantra-3dcb4",
              "private_key_id": "ce61bd536326d612e34b8353cba1e4c49322195e",
              "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCYOI4yt8DCBWZz\ntGH87Uxj27vRwCsFtFuRXJd1piJseYWq26ac0lufAobI1HbTbgByaMAdTx+bgooh\n0CqlJ/TKWJqhQsfWJdIyoNQ76jAgWwswQn6VWBcC6U2f4LVyxgJvV06Qz4MuPCsw\n3IV4xkke3HbAX5f+EZC8dNgopmdy8WJ3g1zjcbmBk2MIglkqz7+7mXQk6fSNnez6\nrMHUAJtUakx+UuRXB6IuL0qCSf6AmA5QqFgohndg0DG2nZRnoCo7emXaFEdtnpFg\ntQ9EEVs119wY/HG1I7fFbbD+eUpSHpe5VzrAsNrXGGuOQD5i5ivhZtqeUJZtaQaq\nHH4JVKsDAgMBAAECggEAE1ZGj3V9rH1jIRpZGE2iK/f4nrylZSQe6GhgFTdK8ty9\nI5H4/b2l8J0xjMbwvAsio2YLLFimJesqAQGgvo+aLoTy9RQMBCLp1jn4EWRpQ12i\nyOP+5e860nPbbePt05az2Hu5efaNLjfBL4PUBh5U9karZI9q5NZLvKUF5floStbi\nT8GaalmFsUcRUO29lYr5fVGky71lfvhjggO8nb7Z2niCvTAYWDSRAZk/Zl3WBbsI\nrnPmyn/wYvQlerwQPXd44ryZKZWEbz1dQEdd2sNaqulMsCvwu+dS2LJGZFKC/3xk\nbxovLQnVQ1jJnREcHq/RMZSncwtcfriKHvvVW3K/AQKBgQC8LDFascpanO8bDN5l\n2vH9m8OYln4327lNCpNlebzAiJPFXBSzJl7dW1utwmiAJOH5gM4l+9zasVX7Mikm\nitnf9GWHkd55TN7k69BVnF6zDMv9hF/IZ4BjQpsg30XHrdxDZgh+eZ6r3EB6GvY7\nCbwBCTwnG/Er/cPeBzQZLWBjiQKBgQDPFuKBapqT3DamsQz0W+ciyrTUQcRB+PgQ\ncr8KTuyzzmOmxic59Gc28K/UhUE3Et0pWQ8rf+4n/ox8QC82d1nbQ/X/tiEJ1zj5\nxZop7YYL7JLFCJ7t8OVLp5CAAuJFPsNwV/ElV4WRIxU1Kk76f6pAxu5mhZD1CCwF\nTz//xuCbKwKBgDlvs9DfG8j0xfcXwnqMjfi/JsDYjsY2ByWA6OS8d+S8y34eUSMt\nvx8J17397S/QEjm6GzJ04kDOiFQYR39AOqilTKhI2gNkd1SgtgKrrCwy58EGOsZM\n8V9a4UbzX7VHWEgqSMVyEgCbRgL/X9E9c2lNjFLTsJWg67xFrp1QwG8hAoGANnBB\notuvPudIxpEMYsA2BoNa/eE8Aku8ijZf2gndV3cN4y176lRBPcQPtMJC3oNq+A+d\nWUYMCR91NsR4pMzDJky7QjlSfg/Bvocfe54g+sl526nkfZAx9q1Z4wzfBmz1W3cC\nwVo8lmaukIdKs7cTvmuNCA5ciM1ZJRwsKsTRDnkCgYEApESQRYe0F0eO3kpbELUG\n+YRhcUD4LAw5kZKlljsM+dKBd4Wm28zTtfPGPDW8w/kvPD59KwYad4m5+fNIdogY\n+07rUN5CTHmX6PVbAxS8Oa5DDawbtZWhAVQillXl7Jl+GIeYK5X9q7kcynzKWXMU\neT94LHec3EJYBQhIhuVxL0k=\n-----END PRIVATE KEY-----\n",
              "client_email": "firebase-adminsdk-zohhh@plantra-3dcb4.iam.gserviceaccount.com",
              "client_id": "117926072151254517223",
              "auth_uri": "https://accounts.google.com/o/oauth2/auth",
              "token_uri": "https://oauth2.googleapis.com/token",
              "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
              "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-zohhh%40plantra-3dcb4.iam.gserviceaccount.com",
              "universe_domain": "googleapis.com"
        }

        # 서비스 계정 정보로 인증서 생성
        credentials = service_account.Credentials.from_service_account_info(
            service_account_info,
            scopes=["https://www.googleapis.com/auth/cloud-platform"]
        )
        credentials.refresh(Request())
        return credentials.token

    @classmethod
    def send_message(cls, title: str, body: str, token: str, data: dict = None) -> bool:
        """FCM 알림 전송"""
        try:
            access_token = cls.get_access_token()

            # HTTP v1 API URL 구성
            project_id = current_app.config.get("FCM_PROJECT_ID")
            url = f"https://fcm.googleapis.com/v1/projects/{project_id}/messages:send"

            # 메시지 생성
            message = {
                "message": {
                    "token": token,
                    "notification": {
                        "title": title,
                        "body": body
                    },
                    "data": data or {}
                }
            }

            # 헤더 설정
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json"
            }

            # POST 요청 전송
            response = requests.post(url, headers=headers, data=json.dumps(message))

            if response.status_code == 200:
                logger.info(f"메시지 전송 성공: {response.json()}")
                return True
            else:
                logger.error(f"메시지 전송 실패: {response.status_code}, {response.text}")
                return False

        except Exception as e:
            logger.error(f"[FCM][send_message] 오류: {e}")
            return False



# # 테스트용 API 라우트
# @app.route('/send_notification', methods=['POST'])
# def send_notification():
#     """FCM 알림 전송 API"""
#     data = request.json
#     title = data.get('title')
#     body = data.get('body')
#     token = data.get('token')
#     custom_data = data.get('data')

#     if not title or not body or not token:
#         return jsonify({"error": "title, body, and token are required"}), 400

#     success = FCM.send_message(title, body, token, custom_data)
#     if success:
#         return jsonify({"message": "알림 전송 성공"}), 200
#     else:
#         return jsonify({"error": "알림 전송 실패"}), 500

# if __name__ == '__main__':
#     # 애플리케이션 컨텍스트를 명시적으로 설정
#     with app.app_context():
#         test_title = "테스트 알림 - json 포함방식 "
#         test_body = "- json 포함방식 이것은 테스트 메시지입니다."
#         test_token = "f9lH_mhpa06kmiKKXntp-k:APA91bEBScu9qDiBLi2973-zAgFdRlab1a1LmCpjFxtLttdcq93WBl2ykSo59s4ZeAQJhySn81kCb2FrWHGY7v4AudX0um3sPvzmxKxacXqsSILEMrR1qOrh7qi2Nqj7mR7awSPEGrFT"
#         test_data = {
#             "key1": "value1",
#             "key2": "value2"
#         }

#         success = FCM.send_message(test_title, test_body, test_token, test_data)
    
#         if success:
#             print("테스트 메시지 전송 성공!")
#         else:
#             print("테스트 메시지 전송 실패.")

#         # Flask 앱 실행
#         app.run(debug=True)



