# Complete PYOMO implementation - Retry Attempt 4

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

def allergy_accommodation_optimization():
    """Optimization model for allergy accommodation problem."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define sets for allergy types and cities
    allergy_types = ['peanut', 'dairy', 'gluten']
    cities = ['NYC', 'LA', 'CHI']
    
    # Define cost data
    cost_data = {
        ('peanut', 'NYC'): 120.0,
        ('dairy', 'LA'): 100.0,
        ('gluten', 'CHI'): 90.0
    }
    
    # Validate cost data for all combinations
    for i in allergy_types:
        for j in cities:
            if (i, j) not in cost_data:
                raise ValueError(f"Missing cost data for {i} in {j}")
    
    # 3. SETS
    model.allergy_types = pyo.Set(initialize=allergy_types)
    model.cities = pyo.Set(initialize=cities)
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.allergy_types, model.cities, initialize=cost_data)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.allergy_types, model.cities, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[i, j] * model.x[i, j] for i in model.allergy_types for j in model.cities)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Budget Constraint
    def budget_rule(model):
        return sum(model.cost[i, j] * model.x[i, j] for i in model.allergy_types for j in model.cities) <= 500000
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Minimum Resource Requirement
    def min_resource_rule(model, i, j):
        return model.x[i, j] >= 5
    model.min_resource_constraint = pyo.Constraint(model.allergy_types, model.cities, rule=min_resource_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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.allergy_types:
            for j in model.cities:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i}, {j}] = {x_val:.3f}")
        
    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

# Execute the optimization
if __name__ == "__main__":
    allergy_accommodation_optimization()