# Complete PYOMO implementation

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

def climbing_optimization():
    """Climbing competition optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    climbers = [1, 2, 3]
    mountains = [1, 2, 3]
    points = {1: 15, 2: 25, 3: 10}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(climbers) == len(points), "Array length mismatch for climbers and points"
    
    # 3. SETS
    model.C = pyo.Set(initialize=climbers)
    model.M = pyo.Set(initialize=mountains)
    
    # 4. PARAMETERS
    model.points = pyo.Param(model.C, initialize=points)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.C, model.M, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.points[i] * model.x[i, j] for i in model.C for j in model.M)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Each climber must be assigned to exactly one mountain
    def climber_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.M) == 1
    model.climber_assignment = pyo.Constraint(model.C, rule=climber_assignment_rule)
    
    # Each mountain must have at least one climber assigned to it
    def mountain_assignment_rule(model, j):
        return sum(model.x[i, j] for i in model.C) >= 1
    model.mountain_assignment = pyo.Constraint(model.M, rule=mountain_assignment_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)
    
    # 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 climbers to mountains:")
        for i in model.C:
            for j in model.M:
                if pyo.value(model.x[i, j]) > 0.5:  # Only print assignments
                    print(f"Climber {i} assigned to Mountain {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
climbing_optimization()