import functions_framework
import os
import datetime
from google.cloud import bigquery

# Initializing (Global Scope)
bq_client = bigquery.Client()

TABLE_ID = "esp32-c3-temp-to-gcp.tempdb.sensor_readings"

@functions_framework.http
def log_sensor_data(request):

    # Get the secret key from environment
    API_KEY = os.environ.get('SECRET_API_KEY')
    # Security Check
    client_key = request.headers.get('x-api-key')

    if not API_KEY or client_key != API_KEY:
        return "Unauthorized", 401

    try:
        request_json = request.get_json(silent=True)
        
        if request_json and 'temperature' in request_json:
            
            row_to_insert = [
                {
                    "temperature": float(request_json['temperature']),
                    "timestamp": datetime.datetime.utcnow().isoformat()
                }
            ]
            
            # Insert into BigQuery
            errors = bq_client.insert_rows_json(TABLE_ID, row_to_insert)
            
            if errors == []:
                return "Data saved to BigQuery", 200
            else:
                return f"BigQuery Insert Errors: {errors}", 500

        else:
            return "Invalid JSON: Missing temperature", 400

    except Exception as e:
        print(f"Error: {e}")
        return f"Internal Error: {e}", 500