#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for News Agency Optimization Problem
"""

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

def news_agency_optimization():
    """Optimize journalist assignments to events to maximize coverage quality."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Journalist data: Years_working and max_assignments
    journalists = {
        1: {'Years_working': 5, 'max_assignments': 3},
        2: {'Years_working': 10, 'max_assignments': 4},
        3: {'Years_working': 15, 'max_assignments': 5}
    }
    
    # Event data: Event_Attendance
    events = {
        1: {'Event_Attendance': 100},
        2: {'Event_Attendance': 200},
        3: {'Event_Attendance': 300}
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(journalists) > 0 and len(events) > 0, "Data arrays must not be empty"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=journalists.keys())  # Journalists
    model.J = pyo.Set(initialize=events.keys())      # Events
    
    # 4. PARAMETERS (data containers)
    model.Years_working = pyo.Param(model.I, initialize={i: journalists[i]['Years_working'] for i in model.I})
    model.max_assignments = pyo.Param(model.I, initialize={i: journalists[i]['max_assignments'] for i in model.I})
    model.Event_Attendance = pyo.Param(model.J, initialize={j: events[j]['Event_Attendance'] for j in model.J})
    
    # 5. VARIABLES
    # Binary decision variables: x[i,j] = 1 if journalist i is assigned to event j
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total coverage quality
    def obj_rule(model):
        return sum(model.Years_working[i] * model.Event_Attendance[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
    
    # Event Coverage Requirement: Each event must be covered by at least one journalist
    def event_coverage_rule(model, j):
        return sum(model.x[i,j] for i in model.I) >= 1
    model.event_coverage = pyo.Constraint(model.J, rule=event_coverage_rule)
    
    # Journalist Assignment Limit: No journalist can be assigned to more than their max_assignments
    def journalist_limit_rule(model, i):
        return sum(model.x[i,j] for j in model.J) <= model.max_assignments[i]
    model.journalist_limit = pyo.Constraint(model.I, rule=journalist_limit_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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("\nAssignment details:")
        for i in model.I:
            for j in model.J:
                if pyo.value(model.x[i,j]) > 0.5:  # Only print assignments
                    print(f"Journalist {i} assigned to 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

# Execute the optimization
if __name__ == "__main__":
    news_agency_optimization()