# Complete PYOMO implementation

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

def candidate_poll_optimization():
    """Optimization for candidate poll resource allocation"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    poll_sources = [1, 2, 3]
    support_rates = {1: 0.55, 2: 0.75, 3: 0.6}
    min_efforts = {1: 5.0, 2: 10.0, 3: 7.5}
    max_efforts = {1: 20.0, 2: 30.0, 3: 25.0}
    total_budget = 50.0  # Example budget constraint
    
    # CRITICAL: Validate array lengths before indexing
    assert len(support_rates) == len(min_efforts) == len(max_efforts) == len(poll_sources), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=poll_sources)
    
    # 4. PARAMETERS
    model.support_rate = pyo.Param(model.I, initialize=support_rates)
    model.min_effort = pyo.Param(model.I, initialize=min_efforts)
    model.max_effort = pyo.Param(model.I, initialize=max_efforts)
    
    # 5. VARIABLES
    model.effort = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.support_rate[i] * model.effort[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total budget constraint
    def budget_constraint_rule(model):
        return sum(model.effort[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_rule)
    
    # Minimum and maximum effort constraints
    def effort_bounds_rule(model, i):
        return (model.min_effort[i], model.effort[i], model.max_effort[i])
    model.effort_bounds = pyo.Constraint(model.I, rule=effort_bounds_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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective):.3f}")
        
        # Extract variable values
        print("\nEffort allocation:")
        for i in model.I:
            effort_val = pyo.value(model.effort[i])
            print(f"Effort for poll source {i}: {effort_val:.3f}")
        
    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
candidate_poll_optimization()