# Complete PYOMO implementation

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

def news_report_optimization():
    """Optimize journalist assignments to maximize event attendance"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Event attendance data
    event_attendance = {1: 150, 2: 250, 3: 100}
    # Journalists and events
    journalists = [1, 2, 3]
    events = [1, 2, 3]
    
    # CRITICAL: Validate data lengths before indexing
    assert len(event_attendance) == len(events), "Event data length mismatch"
    
    # 3. SETS
    model.Journalists = pyo.Set(initialize=journalists)
    model.Events = pyo.Set(initialize=events)
    
    # 4. PARAMETERS
    model.EventAttendance = pyo.Param(model.Events, initialize=event_attendance)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Journalists, model.Events, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.EventAttendance[j] * model.x[i, j] for i in model.Journalists for j in model.Events)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Each journalist can cover up to 2 events
    def journalist_constraint_rule(model, i):
        return sum(model.x[i, j] for j in model.Events) <= 2
    model.journalist_constraint = pyo.Constraint(model.Journalists, rule=journalist_constraint_rule)
    
    # Each event can be covered by up to 2 journalists
    def event_constraint_rule(model, j):
        return sum(model.x[i, j] for i in model.Journalists) <= 2
    model.event_constraint = pyo.Constraint(model.Events, rule=event_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("\nAssignment of journalists to events:")
        for i in model.Journalists:
            for j in model.Events:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assignments
                    print(f"Journalist {i} covers Event {j}")
        
    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
news_report_optimization()