# Complete PYOMO implementation

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

def restaurant_marketing_optimization():
    """Optimize marketing budget allocation across cities to maximize rating improvement."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    city_ids = [1, 2, 3]
    coefficients = {1: 0.15, 2: 0.25, 3: 0.10}
    total_budget = 100000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(coefficients) == len(city_ids), "Array length mismatch"
    
    # 3. SETS
    model.C = pyo.Set(initialize=city_ids)
    
    # 4. PARAMETERS
    model.coefficient = pyo.Param(model.C, initialize=coefficients)
    
    # 5. VARIABLES
    model.allocation = pyo.Var(model.C, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.coefficient[c] * model.allocation[c] for c in model.C)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def budget_constraint_rule(model):
        return sum(model.allocation[c] for c in model.C) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_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):.3f}")
        
        # Extract variable values
        print("\nBudget Allocations:")
        for c in model.C:
            allocation_val = pyo.value(model.allocation[c])
            if allocation_val > 1e-6:  # Only print non-zero values
                print(f"City {c}: {allocation_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

# Run the optimization
restaurant_marketing_optimization()