#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Election Representative Optimization
"""

import gurobipy as gp
from gurobipy import GRB

def election_representative_optimization():
    """Optimize campaign resource allocation to maximize seats won."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("election_representative")
    
    # Data from the database
    seats = [1, 2, 3]  # From election.Seats
    resource_allocation = [1000.0, 2000.0, 3000.0]  # From resource_allocation.Resource_Amount
    state_limits = [50000, 60000, 70000]  # From state_resource_limits.Maximum_Resource_Allocation
    
    # Business configuration
    total_budget = 1000000
    min_resource = 1000
    
    # CRITICAL: Validate array lengths before loops
    n_representatives = len(seats)
    assert len(resource_allocation) == n_representatives, "Resource allocation array length mismatch"
    assert len(state_limits) == n_representatives, "State limits array length mismatch"
    
    # 2. VARIABLES
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=min_resource) 
         for i in range(n_representatives)}
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(seats[i] * x[i] for i in range(n_representatives)), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    model.addConstr(gp.quicksum(x[i] for i in range(n_representatives)) <= total_budget, name="total_budget")
    
    # State Resource Limit Constraints
    for i in range(n_representatives):
        model.addConstr(x[i] <= state_limits[i], name=f"state_limit_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_representatives):
            print(f"x[{i}] = {x[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

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