import os
import json
import numpy as np
import traceback
import gspy

# Shared data file written by web_app.py.
# Located in the same directory as this script.
_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_FILE = os.path.join(_DIR, "web_data.json")

# Hard-coded defaults — used when web_data.json does not exist yet.
_DEFAULTS = {
    "indoor_unit_demand": 60.0,
    "outdoor_unit_demand": 150.0,
    "crop_areas": [120, 45, 33],
}


def _load_data() -> dict:
    """Return current values from web_data.json, falling back to defaults."""
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, "r") as f:
                return json.load(f)
        except Exception:
            gspy.log("Could not read web_data.json, using defaults.", 1)
    return dict(_DEFAULTS)


def process_data(*args):
    """
    Called by GoldSim each timestep via the GSPy_ToGS.dll.

    Outputs (in order matching GSPy_ToGS.json):
        1. indoor_unit_demand  - scalar
        2. outdoor_unit_demand - scalar
        3. crop_areas          - vector of 3 values
    """
    try:
        data = _load_data()

        indoor_unit_demand = float(data["indoor_unit_demand"])
        outdoor_unit_demand = float(data["outdoor_unit_demand"])
        crop_areas = np.array(data["crop_areas"], dtype=float)

        gspy.log(f"indoor_unit_demand = {indoor_unit_demand}", 2)
        gspy.log(f"outdoor_unit_demand = {outdoor_unit_demand}", 2)
        gspy.log(f"crop_areas = {crop_areas}", 2)

        # Return a tuple — order must match the 'outputs' list in GSPy_ToGS.json
        return (indoor_unit_demand, outdoor_unit_demand, crop_areas)

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