# Complete PYOMO implementation

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

def entertainment_awards_optimization():
    """Optimize artwork nominations for maximum audience impact."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided problem context
    num_artworks = 3
    num_festivals = 3
    audience_sizes = [1200, 4500, 9000]
    max_nominations_per_artwork = [3, 5, 7]
    max_capacity_per_festival = [50, 100, 150]
    
    # CRITICAL: Validate array lengths before indexing
    assert len(audience_sizes) == num_festivals, "Audience sizes length mismatch"
    assert len(max_nominations_per_artwork) == num_artworks, "Max nominations length mismatch"
    assert len(max_capacity_per_festival) == num_festivals, "Max capacity length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, num_artworks)  # Artworks
    model.J = pyo.RangeSet(1, num_festivals)  # Festivals
    
    # 4. PARAMETERS
    model.audience_size = pyo.Param(model.J, initialize={j+1: audience_sizes[j] for j in range(num_festivals)})
    model.max_nominations = pyo.Param(model.I, initialize={i+1: max_nominations_per_artwork[i] for i in range(num_artworks)})
    model.max_capacity = pyo.Param(model.J, initialize={j+1: max_capacity_per_festival[j] for j in range(num_festivals)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.audience_size[j] * sum(model.x[i, j] for i in model.I) for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Maximum nominations per artwork
    def max_nominations_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= model.max_nominations[i]
    model.max_nominations_constraint = pyo.Constraint(model.I, rule=max_nominations_rule)
    
    # Maximum capacity per festival
    def max_capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.max_capacity[j]
    model.max_capacity_constraint = pyo.Constraint(model.J, rule=max_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("\nVariable values:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i},{j}] = {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

# Run the optimization
entertainment_awards_optimization()