# Complete PYOMO implementation

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

def election_representative_optimization():
    """Optimization model for maximizing seats won by allocating campaign resources."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the database schema and realistic data
    seats = [1, 2, 3]  # From election.Seats
    min_resource = 1000  # Minimum resource allocation
    total_budget = 1000000  # Total budget
    state_limits = [50000, 60000, 70000]  # From state_resource_limits.Maximum_Resource_Allocation
    
    # CRITICAL: Validate array lengths before indexing
    n_reps = len(seats)
    assert len(state_limits) == n_reps, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_reps)  # 1-based indexing for representatives
    
    # 4. PARAMETERS (data containers)
    model.seats = pyo.Param(model.I, initialize={i+1: seats[i] for i in range(n_reps)})
    model.state_limits = pyo.Param(model.I, initialize={i+1: state_limits[i] for i in range(n_reps)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)  # Resource allocation to each representative
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.seats[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total 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)
    
    # Minimum Resource Allocation Constraint
    def min_resource_rule(model, i):
        return model.x[i] >= min_resource
    model.min_resource_constraint = pyo.Constraint(model.I, rule=min_resource_rule)
    
    # State Resource Limit Constraint
    def state_limit_rule(model, i):
        return model.x[i] <= model.state_limits[i]
    model.state_limit_constraint = pyo.Constraint(model.I, rule=state_limit_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("\nResource allocations:")
        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__":
    election_representative_optimization()