# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def real_estate_optimization():
    """Optimization model for maximizing profit from real estate properties"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Property data
    agreed_selling_prices = [120000.0, 180000.0, 250000.0, 95000.0, 130000.0]
    vendor_requested_prices = [110000.0, 170000.0, 240000.0, 90000.0, 125000.0]
    room_counts = [3, 4, 5, 2, 3]
    features = ['desired_feature', 'other_feature', 'desired_feature', 'desired_feature', 'other_feature']
    
    # Constraint bounds
    max_properties_to_sell = 3
    max_total_rooms = 12
    min_desired_features = 2
    
    # CRITICAL: Validate array lengths before indexing
    n_properties = len(agreed_selling_prices)
    assert len(vendor_requested_prices) == len(room_counts) == len(features) == n_properties, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_properties)  # 1-based indexing
    
    # 4. PARAMETERS
    model.agreed_price = pyo.Param(model.I, initialize={i+1: agreed_selling_prices[i] for i in range(n_properties)})
    model.vendor_price = pyo.Param(model.I, initialize={i+1: vendor_requested_prices[i] for i in range(n_properties)})
    model.room_count = pyo.Param(model.I, initialize={i+1: room_counts[i] for i in range(n_properties)})
    model.feature = pyo.Param(model.I, initialize={i+1: features[i] for i in range(n_properties)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((model.agreed_price[i] - model.vendor_price[i]) * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Maximum number of properties to sell
    def max_properties_rule(model):
        return sum(model.x[i] for i in model.I) <= max_properties_to_sell
    model.max_properties_constraint = pyo.Constraint(rule=max_properties_rule)
    
    # Maximum total number of rooms
    def max_rooms_rule(model):
        return sum(model.room_count[i] * model.x[i] for i in model.I) <= max_total_rooms
    model.max_rooms_constraint = pyo.Constraint(rule=max_rooms_rule)
    
    # Minimum number of properties with desired feature
    def min_desired_features_rule(model):
        return sum(model.x[i] for i in model.I if model.feature[i] == 'desired_feature') >= min_desired_features
    model.min_desired_features_constraint = pyo.Constraint(rule=min_desired_features_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected properties:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 0.5:  # Only print selected properties
                print(f"Property {i} selected")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

# Run the optimization
real_estate_optimization()