# Complete PYOMO implementation - Retry Attempt 4

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

def device_distribution_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    devices = [1, 2, 3]
    shops = [101, 102, 103]
    
    shipping_cost = {
        (1, 101): 12.5,
        (2, 102): 18.0,
        (3, 103): 15.0
    }
    
    demand = {
        (1, 101): 60,
        (2, 102): 80,
        (3, 103): 70
    }
    
    storage_capacity = {
        101: 250,
        102: 300,
        103: 200
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(shipping_cost) == len(demand) == len(devices) * len(shops), "Data length mismatch"
    
    # 3. SETS
    model.devices = pyo.Set(initialize=devices)
    model.shops = pyo.Set(initialize=shops)
    
    # 4. PARAMETERS
    model.shipping_cost = pyo.Param(model.devices, model.shops, initialize=shipping_cost)
    model.demand = pyo.Param(model.devices, model.shops, initialize=demand)
    model.storage_capacity = pyo.Param(model.shops, initialize=storage_capacity)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.devices, model.shops, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.shipping_cost[d, s] * model.x[d, s] for d in model.devices for s in model.shops)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Demand Fulfillment
    def demand_fulfillment_rule(model, d, s):
        return model.x[d, s] >= model.demand[d, s]
    model.demand_fulfillment = pyo.Constraint(model.devices, model.shops, rule=demand_fulfillment_rule)
    
    # Storage Capacity
    def storage_capacity_rule(model, s):
        return sum(model.x[d, s] for d in model.devices) <= model.storage_capacity[s]
    model.storage_capacity_constraint = pyo.Constraint(model.shops, rule=storage_capacity_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 d in model.devices:
            for s in model.shops:
                x_val = pyo.value(model.x[d, s])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{d}, {s}] = {x_val:.3f}")
        
    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__":
    device_distribution_optimization()