# Complete PYOMO implementation

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

def optimize_theme_gallery():
    """Optimize the theme gallery's annual revenue from exhibitions."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Artist data
    artist_ids = [1, 2, 3]
    max_exhibitions = {1: 5, 2: 6, 3: 4}
    
    # Exhibition data
    exhibition_ids = [1, 2, 3]
    min_artists = {1: 3, 2: 4, 3: 3}
    ticket_prices = {1: 50, 2: 70, 3: 60}
    
    # Attendance data
    attendance = {
        (1, 1): 100,
        (2, 2): 200,
        (3, 3): 150
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(artist_ids) == len(max_exhibitions), "Artist data length mismatch"
    assert len(exhibition_ids) == len(min_artists) == len(ticket_prices), "Exhibition data length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=artist_ids)  # Set of artists
    model.J = pyo.Set(initialize=exhibition_ids)  # Set of exhibitions
    
    # 4. PARAMETERS (data containers)
    model.max_exhibitions = pyo.Param(model.I, initialize=max_exhibitions)
    model.min_artists = pyo.Param(model.J, initialize=min_artists)
    model.ticket_prices = pyo.Param(model.J, initialize=ticket_prices)
    model.attendance = pyo.Param(model.I, model.J, initialize=attendance)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.ticket_prices[j] * model.attendance[i, j] * 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
    # Artist Availability Constraint
    def artist_availability_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= model.max_exhibitions[i]
    model.artist_availability = pyo.Constraint(model.I, rule=artist_availability_rule)
    
    # Exhibition Requirement Constraint
    def exhibition_requirement_rule(model, j):
        return sum(model.x[i, j] for i in model.I) >= model.min_artists[j]
    model.exhibition_requirement = pyo.Constraint(model.J, rule=exhibition_requirement_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(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}] = {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
if __name__ == "__main__":
    optimize_theme_gallery()