# Complete PYOMO implementation - Retry Attempt 3

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

def device_allocation_optimization():
    """Optimize device allocation to maximize sales potential across shops."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define the data based on the provided database schema and current stored values
    shops = [1, 2, 3]
    devices = [101, 102, 103]
    
    potential_sales_data = {
        (1, 101): 600.0,
        (2, 102): 850.0,
        (3, 103): 950.0
    }
    
    shop_capacity_data = {
        1: 120,
        2: 180,
        3: 220
    }
    
    # 3. SETS
    model.Shops = pyo.Set(initialize=shops)
    model.Devices = pyo.Set(initialize=devices)
    
    # 4. PARAMETERS
    model.potential_sales = pyo.Param(model.Shops * model.Devices, initialize=potential_sales_data, within=pyo.NonNegativeReals)
    model.capacity = pyo.Param(model.Shops, initialize=shop_capacity_data, within=pyo.NonNegativeIntegers)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Shops, model.Devices, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.potential_sales[i, j] * model.x[i, j] for i in model.Shops for j in model.Devices)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def capacity_constraint_rule(model, i):
        return sum(model.x[i, j] for j in model.Devices) <= model.capacity[i]
    model.capacity_constraint = pyo.Constraint(model.Shops, rule=capacity_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)
    
    # 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("\nDevice allocation:")
        for i in model.Shops:
            for j in model.Devices:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0:
                    print(f"Shop {i}, Device {j}: {x_val} units")
        
    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
device_allocation_optimization()