# Complete PYOMO implementation

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

def real_estate_optimization():
    """Optimization model for maximizing real estate revenue."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    properties = {
        1: {'vendor_price': 300000, 'buyer_price': 340000, 'features': [0.15, 0.1]},
        2: {'vendor_price': 450000, 'buyer_price': 500000, 'features': [0.2]},
        3: {'vendor_price': 240000, 'buyer_price': 280000, 'features': [0.1]}
    }
    
    # CRITICAL: Validate data consistency
    for prop_id, data in properties.items():
        assert data['vendor_price'] <= data['buyer_price'], f"Property {prop_id} has invalid price range"
        assert all(0 <= score <= 1 for score in data['features']), f"Property {prop_id} has invalid feature scores"
    
    # 3. SETS
    model.I = pyo.Set(initialize=properties.keys())  # Property IDs
    
    # 4. PARAMETERS
    model.vendor_price = pyo.Param(model.I, initialize={i: properties[i]['vendor_price'] for i in model.I})
    model.buyer_price = pyo.Param(model.I, initialize={i: properties[i]['buyer_price'] for i in model.I})
    model.feature_scores = pyo.Param(model.I, initialize={i: sum(properties[i]['features']) for i in model.I})
    
    # Weighting factor
    feature_weighting_factor = 0.3
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)  # Agreed selling price
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Vendor's Minimum Price Constraint
    def vendor_min_rule(model, i):
        return model.x[i] >= model.vendor_price[i]
    model.vendor_min_constraint = pyo.Constraint(model.I, rule=vendor_min_rule)
    
    # Buyer's Maximum Price Constraint
    def buyer_max_rule(model, i):
        return model.x[i] <= model.buyer_price[i]
    model.buyer_max_constraint = pyo.Constraint(model.I, rule=buyer_max_rule)
    
    # Feature-Adjusted Price Constraint
    def feature_adjusted_rule(model, i):
        return model.x[i] >= model.vendor_price[i] * (1 + feature_weighting_factor * model.feature_scores[i])
    model.feature_adjusted_constraint = pyo.Constraint(model.I, rule=feature_adjusted_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAgreed selling prices:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"Property {i}: {x_val:.2f}")
        
    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
if __name__ == "__main__":
    real_estate_optimization()