# Complete PYOMO implementation

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

def host_city_optimization():
    """Optimization model for selecting host cities for matches."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # City data
    city_ids = [1, 2, 3]
    populations = [800000, 1200000, 600000]
    gdps = [75000.0, 110000.0, 60000.0]
    avg_temperatures = [22.0, 26.0, 20.0]
    hosting_costs = [120000.0, 180000.0, 100000.0]
    
    # Objective weights
    weight_population = 0.4
    weight_gdp = 0.3
    weight_temperature = 0.3
    
    # Constraints
    max_matches_per_city = 2
    total_budget = 1000000.0
    total_matches = 10
    
    # CRITICAL: Validate array lengths before indexing
    assert len(city_ids) == len(populations) == len(gdps) == len(avg_temperatures) == len(hosting_costs), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=city_ids)  # Set of cities
    
    # 4. PARAMETERS
    model.population = pyo.Param(model.I, initialize={i: p for i, p in zip(city_ids, populations)})
    model.gdp = pyo.Param(model.I, initialize={i: g for i, g in zip(city_ids, gdps)})
    model.avg_temperature = pyo.Param(model.I, initialize={i: t for i, t in zip(city_ids, avg_temperatures)})
    model.hosting_cost = pyo.Param(model.I, initialize={i: c for i, c in zip(city_ids, hosting_costs)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers, bounds=(0, max_matches_per_city))  # Number of matches per city
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((weight_population * model.population[i] + 
                    weight_gdp * model.gdp[i] + 
                    weight_temperature * model.avg_temperature[i]) * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total matches constraint
    def total_matches_rule(model):
        return sum(model.x[i] for i in model.I) <= total_matches
    model.total_matches_constraint = pyo.Constraint(rule=total_matches_rule)
    
    # Budget constraint
    def budget_rule(model):
        return sum(model.hosting_cost[i] * model.x[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Maximum matches per city constraint
    def max_matches_rule(model, i):
        return model.x[i] <= max_matches_per_city
    model.max_matches_constraint = pyo.Constraint(model.I, rule=max_matches_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("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.0f}")
        
    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__":
    host_city_optimization()