# Complete PYOMO implementation

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

def performance_attendance_optimization():
    """Optimize the allocation of theater members to performances"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Example data based on the provided schema and realistic data
    member_ids = [1, 2, 3]
    performance_ids = [101, 102, 103]
    attendance_limits = {101: 50, 102: 60, 103: 70}
    member_availability = {1: 5, 2: 10, 3: 15}

    # CRITICAL: Validate array lengths before indexing
    assert len(member_ids) == len(member_availability), "Array length mismatch for members"
    assert len(performance_ids) == len(attendance_limits), "Array length mismatch for performances"

    # 3. SETS
    model.M = pyo.Set(initialize=member_ids)
    model.P = pyo.Set(initialize=performance_ids)

    # 4. PARAMETERS
    model.attendance_limit = pyo.Param(model.P, initialize=attendance_limits)
    model.availability = pyo.Param(model.M, initialize=member_availability)

    # 5. VARIABLES
    model.x = pyo.Var(model.M, model.P, within=pyo.NonNegativeIntegers)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[m, p] for m in model.M for p in model.P)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)

    # 7. CONSTRAINTS

    # Performance Attendance Constraints
    def performance_constraint_rule(model, p):
        return sum(model.x[m, p] for m in model.M) <= model.attendance_limit[p]
    model.performance_constraints = pyo.Constraint(model.P, rule=performance_constraint_rule)

    # Member Availability Constraints
    def member_constraint_rule(model, m):
        return sum(model.x[m, p] for p in model.P) <= model.availability[m]
    model.member_constraints = pyo.Constraint(model.M, rule=member_constraint_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("\nVariable values:")
        for m in model.M:
            for p in model.P:
                x_val = pyo.value(model.x[m, p])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{m},{p}] = {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

# Run the optimization
performance_attendance_optimization()