#!/usr/bin/env python3
"""
ProjectBob.xyz — Get Latest GPS Position from InfluxDB

Fetches the most recent latitude and longitude reported by Bob's
autopilot controllers.

Install:
    pip install influxdb-client

Usage:
    python get_position.py
"""

from influxdb_client import InfluxDBClient

# ---- Connection details (read-only public token) ----
INFLUXDB_URL = "https://us-east-1-1.aws.cloud2.influxdata.com"
INFLUXDB_TOKEN = "PBQmE7mOKmd5U_6krcYOSjBad9_pveomsc8srZME_BfgQpHjaucNQ-4_VYehA7quC7qNLWczAwjFn6OGUMcs3A=="
INFLUXDB_ORG = "littlebob"
INFLUXDB_BUCKET = "littlebob"

# ---- Flux query: latest lat/lon pivoted into one row ----
QUERY = '''
from(bucket: "littlebob")
  |> range(start: -24h)
  |> filter(fn: (r) => r._measurement == "littlebob")
  |> filter(fn: (r) => r._field == "lat" or r._field == "lon")
  |> last()
  |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")
'''


def get_latest_position():
    """Return (lat, lon, timestamp) or None if no data found."""
    with InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG) as client:
        tables = client.query_api().query(QUERY)

        for table in tables:
            for record in table.records:
                lat = record.values.get("lat")
                lon = record.values.get("lon")
                timestamp = record.get_time()
                if lat is not None and lon is not None:
                    return lat, lon, timestamp

    return None


if __name__ == "__main__":
    result = get_latest_position()
    if result:
        lat, lon, ts = result
        print(f"Latest position: {lat:.6f}, {lon:.6f}")
        print(f"Timestamp:       {ts}")
        print(f"Google Maps:     https://www.google.com/maps?q={lat},{lon}")
    else:
        print("No position data found in the last 24 hours.")
