#!/usr/bin/env python3
"""Simple HTTP server that serves FlexMeasures asset locations as JSON."""
import json
import psycopg2
from http.server import HTTPServer, BaseHTTPRequestHandler

def get_assets():
    conn = psycopg2.connect(
        host="flexmeasures-db",
        port=5432,
        database="flexmeasures",
        user="flexmeasures",
        password="Digitribe972"
    )
    cur = conn.cursor()
    cur.execute("""
        SELECT g.name, g.latitude, g.longitude, gt.name as type 
        FROM generic_asset g 
        JOIN generic_asset_type gt ON g.generic_asset_type_id = gt.id 
        ORDER BY gt.id, g.id
    """)
    rows = cur.fetchall()
    cur.close()
    conn.close()
    return [{"name": r[0], "latitude": float(r[1]), "longitude": float(r[2]), "type": r[3]} for r in rows]

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        assets = get_assets()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        self.wfile.write(json.dumps(assets).encode())
    
    def log_message(self, format, *args):
        pass

if __name__ == "__main__":
    server = HTTPServer(("0.0.0.0", 8888), Handler)
    print("Asset location server running on port 8888")
    server.serve_forever()
