# Complete PYOMO implementation

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

def journal_committee_optimization():
    """Optimize editor assignments to journals to maximize sales."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    editors = [1, 2, 3]
    journals = [101, 102, 103]
    sales = {101: 1200.0, 102: 1800.0, 103: 1600.0}
    qualifications = {
        1: ['Science'],
        2: ['Arts'],
        3: ['Technology']
    }
    themes = {
        101: 'Science',
        102: 'Arts',
        103: 'Technology'
    }
    max_journals_per_editor = {1: 2, 2: 2, 3: 2}
    
    # CRITICAL: Validate data consistency
    assert len(editors) == len(max_journals_per_editor), "Editor data mismatch"
    assert len(journals) == len(sales), "Journal data mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=editors)
    model.J = pyo.Set(initialize=journals)
    
    # 4. PARAMETERS
    model.sales = pyo.Param(model.J, initialize=sales)
    model.max_journals = pyo.Param(model.I, initialize=max_journals_per_editor)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.sales[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
    
    # Editor Workload Constraint
    def workload_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= model.max_journals[i]
    model.workload_constraint = pyo.Constraint(model.I, rule=workload_rule)
    
    # Qualification Constraint
    def qualification_rule(model, i, j):
        if themes[j] not in qualifications[i]:
            return model.x[i, j] == 0
        return pyo.Constraint.Skip
    model.qualification_constraint = pyo.Constraint(model.I, model.J, rule=qualification_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
    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 editors to journals:")
        for i in model.I:
            for j in model.J:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Editor {i} 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

# Run the optimization
journal_committee_optimization()