#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Restaurant Placement Optimization
"""

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

def restaurant_optimization():
    """Optimize restaurant placement to maximize customer satisfaction"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    ratings = [4.5, 3.8, 4.2, 3.9, 4.1]
    regions = ['North', 'South', 'East', 'West', 'North']
    
    # CRITICAL: Validate array lengths before indexing
    assert len(ratings) == len(regions), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    n_cities = len(ratings)
    model.I = pyo.RangeSet(1, n_cities)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.rating = pyo.Param(model.I, initialize={i+1: ratings[i] for i in range(n_cities)})
    model.region = pyo.Param(model.I, initialize={i+1: regions[i] for i in range(n_cities)})
    
    # 5. VARIABLES
    # Binary decision variables
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.rating[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total budget constraint
    def budget_rule(model):
        return sum(model.x[i] for i in model.I) <= 5
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Regional distribution constraint
    regions_list = list(set(regions))
    def region_rule(model, r):
        return sum(model.x[i] for i in model.I if model.region[i] == r) >= 1
    model.region_constraint = pyo.Constraint(regions_list, rule=region_rule)
    
    # City-level placement constraint
    def city_rule(model, i):
        return model.x[i] <= 2
    model.city_constraint = pyo.Constraint(model.I, rule=city_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
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected restaurants:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected restaurants
                print(f"City {i}: Rating = {model.rating[i]}, Region = {model.region[i]}")
        
    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__":
    restaurant_optimization()