"""
gs_receiver.py — GoldSim → Python data receiver for B-SOAR
===========================================================
Called by GoldSim each timestep via GSPy_FromGS.dll.

Accepts 2 vectors (in the order defined in GSPy_FromGS.json):
    1. SNF_Initial_Inventory (length 20)
    2. g_WF_DegradationRate (length 4)

We write these vectors to 'gspy_vectors.json' so the AWS worker 
can bundle them into the final results for the frontend.
"""

import json
import os
import traceback
import gspy

_DIR = os.path.dirname(os.path.abspath(__file__))
VECTOR_DATA_FILE = os.path.join(_DIR, "gspy_vectors.json")

def process_data(*args):
    """
    Receives 5 vectors from GoldSim.
    Returns status 1.0.
    """
    try:
        if len(args) < 5:
            gspy.log(f"Expected 5 inputs, got {len(args)}.", 1)
            return (0.0,)

        # Convert numpy arrays to clean Python lists
        snf_initial_inventory = [float(v) for v in args[0].tolist()]
        g_wf_degradation_rate = [float(v) for v in args[1].tolist()]
        smox_initial_inventory = [float(v) for v in args[2].tolist()]
        hlwg_initial_inventory = [float(v) for v in args[3].tolist()]
        hlwc_initial_inventory = [float(v) for v in args[4].tolist()]

        gspy.log(f"Received SNF_Initial_Inventory (size {len(snf_initial_inventory)})", 2)
        gspy.log(f"Received g_WF_DegradationRate (size {len(g_wf_degradation_rate)})", 2)
        gspy.log(f"Received sMOX_Initial_Inventory (size {len(smox_initial_inventory)})", 2)
        gspy.log(f"Received HLWg_Initial_Inventory (size {len(hlwg_initial_inventory)})", 2)
        gspy.log(f"Received HLWc_Initial_Inventory (size {len(hlwc_initial_inventory)})", 2)

        payload = {
            "snf_initial_inventory": snf_initial_inventory,
            "g_wf_degradation_rate": g_wf_degradation_rate,
            "smox_initial_inventory": smox_initial_inventory,
            "hlwg_initial_inventory": hlwg_initial_inventory,
            "hlwc_initial_inventory": hlwc_initial_inventory
        }

        with open(VECTOR_DATA_FILE, "w") as f:
            json.dump(payload, f, indent=2)

        gspy.log("gspy_vectors.json updated successfully.", 2)

        return (1.0,)

    except Exception:
        gspy.log("Error in gs_receiver.process_data:\n" + traceback.format_exc(), 0)
        return (0.0,)
