import sys
import json
import numpy as np
import joblib

# Global variables to keep the model in memory
MODEL = None


MODEL_PATH = '/path/to/price_model.joblib'

def load_model():
    """Load the model if it's not already loaded"""
    global MODEL, MODEL_PATH
    if MODEL is None:
        MODEL = joblib.load(MODEL_PATH)
    return MODEL

def predict_price(x):
    """
    Predicts price using joblib-saved model
    """
    try:
        x = float(x)
    except (ValueError, TypeError):
        raise ValueError(f"Invalid x value: {x}. Must be a number.")
    
    # Load the model (only happens once)
    model = load_model()
    
    # Reshape x for prediction
    x_reshaped = np.array([[x]])
    
    # Make prediction
    price = model.predict(x_reshaped)[0]
    
    # Ensure a reasonable price
    if price < 100:
        price = 100
    
    return float(price)

if __name__ == "__main__":
    try:
        # Parse input JSON from command line
        input_data = json.loads(sys.argv[1])
        print(input_data)
        x = input_data['x']

        # Override model path if provided
        if 'job_path' in input_data:
            MODEL_PATH = input_data['job_path']
        
        # Calculate and output price
        price = predict_price(x)
        print(price)
    except Exception as e:
        # Print error and exit with non-zero status
        print(f"Error: {str(e)}", file=sys.stderr)
        sys.exit(1)
