# Complete PYOMO implementation

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

def optimize_product_allocation():
    """Optimize product allocation across stores to maximize sales revenue."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data from the problem context
    sales_potential_data = {
        (1, 101): 50.0,
        (1, 102): 75.0,
        (1, 103): 100.0
    }
    
    product_availability_data = {
        101: 500,
        102: 750,
        103: 1000
    }
    
    store_capacity_data = {
        1: 1000,
        2: 1500,
        3: 2000
    }
    
    # Validate data lengths
    assert len(sales_potential_data) > 0, "Sales potential data is empty"
    assert len(product_availability_data) > 0, "Product availability data is empty"
    assert len(store_capacity_data) > 0, "Store capacity data is empty"
    
    # 3. SETS
    # Define sets for stores and products
    model.S = pyo.Set(initialize=store_capacity_data.keys())  # Stores
    model.P = pyo.Set(initialize=product_availability_data.keys())  # Products
    
    # 4. PARAMETERS
    # Sales potential parameter
    model.sales_potential = pyo.Param(model.S, model.P, initialize=sales_potential_data, default=0.0)
    
    # Product availability parameter
    model.available_units = pyo.Param(model.P, initialize=product_availability_data)
    
    # Store capacity parameter
    model.capacity = pyo.Param(model.S, initialize=store_capacity_data)
    
    # 5. VARIABLES
    # Decision variable: Number of units of product p allocated to store s
    model.x = pyo.Var(model.S, model.P, within=pyo.NonNegativeIntegers, bounds=(10, 100))
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total sales revenue
    def obj_rule(model):
        return sum(model.sales_potential[s, p] * model.x[s, p] for s in model.S for p in model.P)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Store Capacity Constraint
    def store_capacity_rule(model, s):
        return sum(model.x[s, p] for p in model.P) <= model.capacity[s]
    model.store_capacity_constraint = pyo.Constraint(model.S, rule=store_capacity_rule)
    
    # Product Availability Constraint
    def product_availability_rule(model, p):
        return sum(model.x[s, p] for s in model.S) <= model.available_units[p]
    model.product_availability_constraint = pyo.Constraint(model.P, rule=product_availability_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("\nAllocation values:")
        for s in model.S:
            for p in model.P:
                x_val = pyo.value(model.x[s, p])
                if x_val > 0:  # Only print non-zero values
                    print(f"Store {s}, Product {p}: {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

# Run the optimization
if __name__ == "__main__":
    optimize_product_allocation()