# Complete PYOMO implementation

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

def phone_market_optimization():
    """Optimize phone stock allocation across markets to maximize revenue."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Phone data
    phone_ids = [1, 2, 3]
    prices = {1: 699.99, 2: 899.99, 3: 999.99}
    
    # Market data
    market_ids = [1, 2, 3]
    max_capacities = {1: 1000, 2: 1500, 3: 2000}
    
    # Minimum stock requirements
    min_stocks = {
        (1, 1): 50,
        (2, 2): 100,
        (3, 3): 150
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(phone_ids) == len(prices), "Phone data length mismatch"
    assert len(market_ids) == len(max_capacities), "Market data length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=phone_ids)  # Phone models
    model.J = pyo.Set(initialize=market_ids)  # Markets
    
    # 4. PARAMETERS (data containers)
    model.price = pyo.Param(model.I, initialize=prices)
    model.max_capacity = pyo.Param(model.J, initialize=max_capacities)
    model.min_stock = pyo.Param(model.I, model.J, initialize=min_stocks, default=0)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.price[i] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Market Capacity Constraint
    def market_capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.max_capacity[j]
    model.market_capacity_constraint = pyo.Constraint(model.J, rule=market_capacity_rule)
    
    # Minimum Stock Requirement Constraint
    def min_stock_rule(model, i, j):
        return model.x[i, j] >= model.min_stock[i, j]
    model.min_stock_constraint = pyo.Constraint(model.I, model.J, rule=min_stock_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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 details:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"Phone {i} in Market {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
if __name__ == "__main__":
    phone_market_optimization()