import requests
import json
import psycopg2
import psycopg2.extensions
from datetime import datetime, timezone
import re
from shapely import wkt

def generate_gr2_triangle_placefile(filename="power_outages_gr2.txt"):
    """
    Generates a GR2Analyst placefile using Triangles and Text for power outages.

    Args:
        filename (str): The name of the placefile to create.
    """
    try:
        conn = psycopg2.connect(host='localhost', database='nws', user='nws', password='nws')
        cursor = conn.cursor()

        cursor.execute("SELECT startguess,outagen,lastchange,st_astext(realareageom),lat,lon,cause, outagen FROM power WHERE cwa = 'RLX' and active = true") # Include outagen in select
        outages = cursor.fetchall()

        with open(filename, "w") as pf:
            pf.write("Refresh: 1\n")
            pf.write("Threshold: 999 nautical_miles\n")
            pf.write("Title: Power Outages (RLX CWA) - Triangles\n")
            pf.write("Font: 1, 11, 0, \"Courier New\"\n")
            pf.write("Color: 255 0 0\n")  # Red for triangles (outage area)

            for outage in outages:
                startguess, outagen_num_db, lastchange, realareageom_wkt, lat, lon, cause, outagen_display_num = outage # Get outagen as outagen_display_num

                # Format hover text (optional for triangles, but can add later if needed)
                hover_text = f"Outage #{outagen_display_num}\\n" # Use outagen_display_num for display
                hover_text += f"Cause: {cause}\\n"
                hover_text += f"Last Update: {lastchange.strftime('%Y-%m-%d %H:%M:%Z UTC')}"

                # Triangle vertices - create a small triangle around the outage point
                triangle_lat_offset = 0.02  # Adjust for triangle size (latitude offset)
                triangle_lon_offset = 0.03  # Adjust for triangle size (longitude offset)

                pf.write("Triangles:\n")
                pf.write(f"  {lat - triangle_lat_offset}, {lon - triangle_lon_offset}\n") # Vertex 1: Southwest
                pf.write(f"  {lat + triangle_lat_offset}, {lon - triangle_lon_offset}\n") # Vertex 2: Southeast
                pf.write(f"  {lat}, {lon + triangle_lon_offset}\n") # Vertex 3: North
                pf.write("End:\n")

                # Blue text label for outage number
                pf.write("Color: 0 0 255\n") # Blue for text
                pf.write(f"Text: {lat}, {lon}, 1, \"Outage #{outagen_display_num}\", \"{hover_text}\"\n") # Include hover text

            pf.write("End:\n")

        print(f"GR2Analyst Triangle placefile '{filename}' generated successfully.")

    except psycopg2.Error as db_error:
        print(f"Database error: {db_error}")
    except IOError as io_error:
        print(f"File I/O error: {io_error}")
    finally:
        if conn:
            conn.close()

if __name__ == "__main__":
    generate_gr2_triangle_placefile()
    # generate_gr2_triangle_placefile("my_outages_triangle.txt")