# Complete PYOMO implementation

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

def optimize_budget_allocation():
    """Optimize budget allocation to maximize population served."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # City data: CityID, Population, DistrictID
    city_data = {
        1: {'Population': 150000, 'DistrictID': 1},
        2: {'Population': 250000, 'DistrictID': 2},
        3: {'Population': 100000, 'DistrictID': 3}
    }
    
    # Total budget and minimum allocations
    total_budget = 1000000
    min_city_allocation = 50000
    min_district_allocation = 200000
    
    # Validate data consistency
    assert len(city_data) == 3, "City data length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=city_data.keys())  # Set of cities
    
    # 4. PARAMETERS
    model.population = pyo.Param(model.I, initialize={i: city_data[i]['Population'] for i in model.I})
    model.district = pyo.Param(model.I, initialize={i: city_data[i]['DistrictID'] for i in model.I})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.population[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Budget Limit
    def total_budget_rule(model):
        return sum(model.x[i] for i in model.I) <= total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    # Minimum Allocation per City
    def min_city_allocation_rule(model, i):
        return model.x[i] >= min_city_allocation
    model.min_city_allocation_constraint = pyo.Constraint(model.I, rule=min_city_allocation_rule)
    
    # Minimum Allocation per District
    def min_district_allocation_rule(model, i):
        return model.x[i] >= min_district_allocation
    model.min_district_allocation_constraint = pyo.Constraint(model.I, rule=min_district_allocation_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)}")
        
        # Extract variable values
        print("\nBudget allocations:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"City {i}: {x_val:.2f}")
        
    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__":
    optimize_budget_allocation()