# Complete PYOMO implementation

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

def local_govt_in_alabama_optimization():
    """Optimize participant assignments to maximize satisfaction scores."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Sample data based on the provided database schema and current stored values
    participants = [1, 2, 3]
    events = [101, 102, 103]
    
    satisfaction_scores = {
        (1, 101): 0.7,
        (1, 102): 0.9,
        (2, 101): 0.6,
        (2, 103): 0.8,
        (3, 102): 0.5
    }
    
    capacity_limits = {
        101: 50,
        102: 100,
        103: 150
    }
    
    # 3. SETS
    model.Participants = pyo.Set(initialize=participants)
    model.Events = pyo.Set(initialize=events)
    
    # 4. PARAMETERS
    model.satisfaction_score = pyo.Param(model.Participants, model.Events, initialize=satisfaction_scores, default=0)
    model.capacity_limit = pyo.Param(model.Events, initialize=capacity_limits)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Participants, model.Events, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.satisfaction_score[i, j] * model.x[i, j] for i in model.Participants for j in model.Events)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Capacity constraints
    def capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.Participants) <= model.capacity_limit[j]
    model.capacity_constraint = pyo.Constraint(model.Events, rule=capacity_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("\nAssignment of participants to events:")
        for i in model.Participants:
            for j in model.Events:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assignments
                    print(f"Participant {i} assigned to Event {j}")
        
    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
local_govt_in_alabama_optimization()