import json
import os
import traceback
from datetime import datetime, timezone
import gspy

_DIR = os.path.dirname(os.path.abspath(__file__))
PROGRESS_DATA_FILE = os.path.join(_DIR, "progress.json")

# Keep track of the last written integer percent in memory so we don't spam the disk
_last_written_percent = -1

def process_data(*args):
    """
    Called by GoldSim each timestep via GSPy_PC.dll.
    Inputs (in order matching GSPy_PC.json):
        1. percent_complete - scalar float
    """
    global _last_written_percent
    try:
        if len(args) < 1:
            gspy.log("Expected at least 1 input value (percent_complete).", 1)
            return (0.0,)
            
        percent_complete = float(args[0])
        current_percent_int = int(percent_complete)
        
        # If the simulation restarts and falls back to 0, reset our tracking marker
        if current_percent_int < _last_written_percent:
            _last_written_percent = -1
            
        # Strictly throttle the heavy disk write to only trigger when the integer increments
        if current_percent_int > _last_written_percent:
            gspy.log(f"percent_complete = {percent_complete:.2f}%", 2)
            
            _last_written_percent = current_percent_int
            
            # Read job_id from web_data.json generated by aws_worker.py
            web_data_path = os.path.join(_DIR, "web_data.json")
            try:
                import urllib.request
                import ssl
                with open(web_data_path, "r") as f:
                    web_data = json.load(f)
                    job_id = web_data.get("simulation_job_id")
                    
                if job_id:
                    # Point this to your active Web Server (use ngrok for local testing if needed)
                    webhook_base = os.getenv("WEBHOOK_URL", "https://lillywhitewater.com/api/job-progress/")
                    if not webhook_base.endswith('/'): webhook_base += '/'
                    
                    payload = json.dumps({"progress": percent_complete}).encode('utf-8')
                    req = urllib.request.Request(f"{webhook_base}{job_id}/", data=payload, headers={'Content-Type': 'application/json'})
                    
                    # Fire and forget with a short timeout so we never bottleneck GoldSim
                    ctx = ssl.create_default_context()
                    ctx.check_hostname = False
                    ctx.verify_mode = ssl.CERT_NONE
                    urllib.request.urlopen(req, timeout=3.0, context=ctx)
            except Exception as e:
                gspy.log(f"Failed to ping WebHook: {str(e)}", 1)
                
        return (1.0,)
    except Exception as e:
        gspy.log(f"Error in gs_progress.process_data:\n{traceback.format_exc()}", 0)
        return (0.0,)
