# Complete PYOMO implementation

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

def store_product_optimization():
    """Optimize product distribution across stores to maximize sales potential."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the database schema
    product_ids = [1, 2, 3]
    store_ids = [1, 2, 3]
    
    sales_values = {1: 12.5, 2: 25.0, 3: 18.0}
    availabilities = {1: 60, 2: 80, 3: 70}
    store_capacities = {1: 120, 2: 180, 3: 150}
    
    # 3. SETS
    model.I = pyo.Set(initialize=product_ids)
    model.J = pyo.Set(initialize=store_ids)
    
    # 4. PARAMETERS
    model.sales_value = pyo.Param(model.I, initialize=sales_values)
    model.availability = pyo.Param(model.I, initialize=availabilities)
    model.store_capacity = pyo.Param(model.J, initialize=store_capacities)
    
    # 5. VARIABLES
    model.units_assigned = pyo.Var(model.I, model.J, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.sales_value[i] * model.units_assigned[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Product Availability Constraint
    def product_availability_rule(model, i):
        return sum(model.units_assigned[i, j] for j in model.J) <= model.availability[i]
    model.product_availability_constraint = pyo.Constraint(model.I, rule=product_availability_rule)
    
    # Store Capacity Constraint
    def store_capacity_rule(model, j):
        return sum(model.units_assigned[i, j] for i in model.I) <= model.store_capacity[j]
    model.store_capacity_constraint = pyo.Constraint(model.J, rule=store_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 i in model.I:
            for j in model.J:
                units_val = pyo.value(model.units_assigned[i, j])
                if units_val > 1e-6:  # Only print non-zero values
                    print(f"units_assigned[{i}, {j}] = {units_val:.0f}")
        
    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
store_product_optimization()