# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_performance_attendance():
    """Optimize the allocation of theater members to performances."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("performance_attendance")
    
    # Data from the database schema
    member_ids = [1, 2, 3]
    performance_ids = [101, 102, 103]
    
    # Attendance limits for each performance
    attendance_limits = {101: 50, 102: 60, 103: 70}
    
    # Member availability
    member_availability = {1: 5, 2: 10, 3: 15}
    
    # Validate data lengths
    assert len(member_ids) == len(member_availability), "Member data length mismatch"
    assert len(performance_ids) == len(attendance_limits), "Performance data length mismatch"
    
    # 2. VARIABLES
    # Decision variables: number of pieces performed by member i in performance j
    x = model.addVars(member_ids, performance_ids, vtype=GRB.INTEGER, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total number of pieces performed
    model.setObjective(gp.quicksum(x[i, j] for i in member_ids for j in performance_ids), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Performance Attendance Constraints
    for j in performance_ids:
        model.addConstr(gp.quicksum(x[i, j] for i in member_ids) <= attendance_limits[j], name=f"attendance_limit_{j}")
    
    # Member Availability Constraints
    for i in member_ids:
        model.addConstr(gp.quicksum(x[i, j] for j in performance_ids) <= member_availability[i], name=f"availability_limit_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in member_ids:
            for j in performance_ids:
                if x[i, j].x > 1e-6:
                    print(f"x[{i},{j}] = {x[i, j].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_performance_attendance()