#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Journal Committee Optimization Problem
"""

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

def journal_committee_optimization():
    """Optimize the assignment of editors to journals to maximize total sales."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Journals and their sales
    journals = {1: 1200.0, 2: 1800.0, 3: 900.0}
    
    # Editors and their maximum workloads
    editors = {1: 4, 2: 3, 3: 5}
    
    # Validate array lengths
    assert len(journals) == 3, "Number of journals mismatch"
    assert len(editors) == 3, "Number of editors mismatch"
    
    # 3. SETS
    model.J = pyo.Set(initialize=journals.keys())  # Journals
    model.E = pyo.Set(initialize=editors.keys())   # Editors
    
    # 4. PARAMETERS
    model.Sales = pyo.Param(model.J, initialize=journals)
    model.Max_Workload = pyo.Param(model.E, initialize=editors)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.E, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Sales[j] * model.x[e, j] for e in model.E for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Editor Workload Constraint
    def workload_rule(model, e):
        return sum(model.x[e, j] for j in model.J) <= model.Max_Workload[e]
    model.workload_constraint = pyo.Constraint(model.E, rule=workload_rule)
    
    # Journal Assignment Constraint
    def assignment_rule(model, j):
        return sum(model.x[e, j] for e in model.E) >= 1
    model.assignment_constraint = pyo.Constraint(model.J, rule=assignment_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("\nAssignment details:")
        for e in model.E:
            for j in model.J:
                if pyo.value(model.x[e, j]) > 0.5:  # Only print assignments
                    print(f"Editor {e} assigned to Journal {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__":
    journal_committee_optimization()