from flask import Blueprint, request, jsonify
from flask_cors import CORS
from firebase.firebase import Firebase
import os
import json
import logging
import base64
import time
from google.cloud import pubsub_v1
logging.basicConfig(level=logging.INFO)

pubsub = Blueprint('pubsub', __name__, url_prefix='/pubsub')

PROJECT_ID = os.environ.get('GCP_PROJECT') 
TOPIC_ID = os.environ.get('PUBSUB_TOPIC_ID')

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(PROJECT_ID, TOPIC_ID)
fb = Firebase(host=os.environ.get("FIREBASE_HOST"))

@pubsub.route('/', methods=['POST'])
@pubsub.route('', methods=['POST'])
def pubsub_log():
    """
    Receives incoming webhook data, publishes it to Pub/Sub.
    """
    try:
        # Get the incoming JSON data
        data = request.get_json(silent=True)

        if not data:
            return jsonify({'error': 'No JSON data received'}), 400
        message_data = json.dumps(data).encode('utf-8')

        # Publish the message to Pub/Sub
        future = publisher.publish(topic_path, message_data)
        message_id = future.result()

        logging.info(f"Published message with ID: {message_id} to topic: {TOPIC_ID}")
        fb.db.reference('webhook_messages').push(data)

        return jsonify({'status': 'success', 'message_id': message_id}), 200

    except Exception as e:
        logging.info(f"Error processing webhook: {e}")
        return jsonify({'error': str(e)}), 500
    
@pubsub.route('/gotmessage', methods=['POST'])
@pubsub.route('/gotmessage/', methods=['POST'])
def receive_message():
    """
    Receives push messages from Pub/Sub.
    """
    try:
        envelope = request.get_json()
        if not envelope:
            raise ValueError('Invalid Pub/Sub message format')

        # Pub/Sub messages are base64 encoded
        message = envelope.get('message')
        if not message:
            raise ValueError('No message found in Pub/Sub envelope')

        data = base64.b64decode(message['data']).decode('utf-8')
        message_id = message.get('messageId')
        publish_time = message.get('publishTime')
        attributes = message.get('attributes')

        # Parse the data (assuming it's JSON from the publisher)
        try:
            parsed_data = json.loads(data)
        except json.JSONDecodeError:
            parsed_data = data # If not JSON, keep as string

        logging.info(f"Received message ID: {message_id}")
        logging.info(f"Published at: {publish_time}")
        logging.info(f"Attributes: {attributes}")
        logging.info(f"Decoded data: {parsed_data}")

        # --- Your data processing logic goes here ---
        # For example, store in BigQuery, update a database, trigger another service, etc.
        # If your processing is asynchronous and might take longer than Cloud Run's timeout,
        # consider pushing to another Pub/Sub topic or Cloud Tasks.
        # -------------------------------------------

        # Acknowledge the message by returning 200 OK
        time.sleep(30)
        return 'OK', 200

    except Exception as e:
        logging.error(f"Error processing Pub/Sub message: {e}")
        # Returning anything other than 200 OK will cause Pub/Sub to retry the message.
        return jsonify({'error': str(e)}), 500