# Complete PYOMO implementation

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

def city_record_optimization():
    """Optimization for match allocation to maximize GDP impact"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    cities = [1, 2, 3]
    matches = [1, 2, 3]
    GDP = {1: 1500.0, 2: 2500.0, 3: 1800.0}
    temperature_data = {
        (1, 'Jan'): (16.0, 24.0),
        (2, 'Jan'): (18.0, 26.0),
        (3, 'Jan'): (15.0, 23.0),
        (1, 'Feb'): (17.0, 25.0),
        (2, 'Feb'): (19.0, 27.0),
        (3, 'Feb'): (16.0, 24.0),
        (1, 'Mar'): (18.0, 26.0),
        (2, 'Mar'): (20.0, 28.0),
        (3, 'Mar'): (17.0, 25.0)
    }
    month = 'Jan'  # Example month for allocation
    
    # CRITICAL: Validate data lengths before indexing
    assert len(cities) == len(GDP), "Mismatch in cities and GDP data length"
    
    # 3. SETS
    model.C = pyo.Set(initialize=cities)
    model.M = pyo.Set(initialize=matches)
    
    # 4. PARAMETERS
    model.GDP = pyo.Param(model.C, initialize=GDP)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.M, model.C, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.GDP[c] * model.x[m, c] for m in model.M for c in model.C)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Each match is allocated to at most one city
    def match_allocation_rule(model, m):
        return sum(model.x[m, c] for c in model.C) <= 1
    model.match_allocation_constraint = pyo.Constraint(model.M, rule=match_allocation_rule)
    
    # Temperature suitability constraint
    def temperature_suitability_rule(model, m, c):
        min_temp, max_temp = temperature_data[(c, month)]
        if min_temp < 15 or max_temp > 27:
            return model.x[m, c] == 0
        return pyo.Constraint.Skip
    model.temperature_suitability_constraint = pyo.Constraint(model.M, model.C, rule=temperature_suitability_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)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nMatch allocations:")
        for m in model.M:
            for c in model.C:
                if pyo.value(model.x[m, c]) > 0.5:  # Binary variable check
                    print(f"Match {m} allocated to City {c}")
        
    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

# Run the optimization
city_record_optimization()