# Complete PYOMO implementation - Retry Attempt 4

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

def candidate_poll_optimization():
    """Optimize the allocation of resources to maximize the overall support rate for a candidate."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    poll_sources = [1, 2, 3]
    support_rates = {1: 0.3, 2: 0.4, 3: 0.5}
    conversion_rates = {1: 0.05, 2: 0.07, 3: 0.1}
    total_budget = 100000
    min_investment = 1000
    max_support_rate = 0.8
    
    # CRITICAL: Validate array lengths before indexing
    assert len(support_rates) == len(conversion_rates) == len(poll_sources), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=poll_sources)
    
    # 4. PARAMETERS (data containers)
    model.support_rate = pyo.Param(model.I, initialize=support_rates)
    model.conversion_rate = pyo.Param(model.I, initialize=conversion_rates)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals, bounds=(min_investment, total_budget))
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.support_rate[i] + model.conversion_rate[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Budget Constraint
    def budget_rule(model):
        return sum(model.x[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Maximum Support Rate Constraint
    def max_support_rate_rule(model, i):
        return model.support_rate[i] + model.conversion_rate[i] * model.x[i] <= max_support_rate
    model.max_support_rate_constraint = pyo.Constraint(model.I, rule=max_support_rate_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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nInvestment values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"x[{i}] = {x_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

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