import functions_framework
from google.cloud import bigquery
import datetime

INTERVAL = 3620
bq_client = bigquery.Client()
TABLE_ID = "esp32-c3-temp-to-gcp.tempdb.sensor_readings"

@functions_framework.http
def check_sensor_health(request):
    
    # 1. Query for the absolute latest timestamp
    query = f"SELECT MAX(timestamp) as latest FROM `{TABLE_ID}`"
    
    try:
        query_job = bq_client.query(query)
        results = query_job.result()
        
        # Get the first (and only) row
        row = next(results)
        latest_time = row.latest

        if latest_time is None:
            return "No data found at all.", 200

        # 2. Check how long ago it was sent
        # BigQuery timestamps are returned as UTC-aware datetime objects
        now = datetime.datetime.now(datetime.timezone.utc)
        diff = now - latest_time

        if diff.total_seconds() > INTERVAL:
            print(f"ALERT: Sensor is silent! Last seen: {latest_time}")
            return f"Sensor Offline. Last seen: {latest_time}", 500
        
        return f"Sensor is Healthy. Last seen: {latest_time}", 200

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