# Complete PYOMO implementation - Retry Attempt 2

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

def optimize_reservations():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Reservation data: Rate and AcceptReservation
    rates = [120.0, 100.0, 150.0, 110.0, 130.0]
    accept_reservation = [1, 0, 1, 1, 0]
    
    # Number of reservations
    n_reservations = len(rates)
    
    # Validate array lengths
    assert len(rates) == len(accept_reservation) == n_reservations, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_reservations)  # 1-based indexing
    
    # 4. PARAMETERS
    model.rate = pyo.Param(model.I, initialize={i+1: rates[i] for i in range(n_reservations)})
    model.accept_reservation = pyo.Param(model.I, initialize={i+1: accept_reservation[i] for i in range(n_reservations)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.rate[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Room Capacity Constraint
    def room_capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= 4
    model.room_capacity_constraint = pyo.Constraint(rule=room_capacity_rule)
    
    # Date Overlap Constraint
    # Assuming overlapping pairs are known and provided
    overlapping_pairs = [(1, 2), (2, 3), (3, 4), (4, 5)]
    
    def date_overlap_rule(model, i, j):
        return model.x[i] + model.x[j] <= 1
    model.date_overlap_constraint = pyo.Constraint(overlapping_pairs, rule=date_overlap_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.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {int(x_val)}")
        
    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
optimize_reservations()