# Complete PYOMO implementation

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

def phone_market_optimization():
    """Optimize phone stock distribution to maximize revenue"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Assuming data is fetched from a database or defined in the script
    markets = [1, 2, 3]
    phones = [101, 102, 103]
    available_stock = {101: 150, 102: 200, 103: 100}
    prices = {101: 299.99, 102: 399.99, 103: 499.99}
    max_stock_capacity = {1: 50, 2: 60, 3: 40}  # Example capacities for each market
    
    # CRITICAL: Validate data lengths before indexing
    assert len(available_stock) == len(prices) == len(phones), "Data length mismatch"
    
    # 3. SETS
    model.M = pyo.Set(initialize=markets)
    model.P = pyo.Set(initialize=phones)
    
    # 4. PARAMETERS
    model.available_stock = pyo.Param(model.P, initialize=available_stock)
    model.price = pyo.Param(model.P, initialize=prices)
    model.max_stock_capacity = pyo.Param(model.M, initialize=max_stock_capacity)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.M, model.P, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.price[p] * model.x[m, p] for m in model.M for p in model.P)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Stock Availability Constraint
    def stock_availability_rule(model, p):
        return sum(model.x[m, p] for m in model.M) <= model.available_stock[p]
    model.stock_availability_constraint = pyo.Constraint(model.P, rule=stock_availability_rule)
    
    # Market Capacity Constraint
    def market_capacity_rule(model, m):
        return sum(model.x[m, p] for p in model.P) <= model.max_stock_capacity[m]
    model.market_capacity_constraint = pyo.Constraint(model.M, rule=market_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):.2f}")
        
        # Extract variable values
        print("\nVariable values:")
        for m in model.M:
            for p in model.P:
                x_val = pyo.value(model.x[m, p])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{m},{p}] = {x_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

# Run the optimization
phone_market_optimization()