# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_phone_distribution():
    """Optimize phone stock distribution to maximize revenue."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="phone_market")
    
    # Data from the database schema
    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}
    
    # Assumed maximum stock capacity for each market
    max_stock_capacity = {1: 100, 2: 150, 3: 80}
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(available_stock) == len(prices) == len(phones), "Array length mismatch"
    safe_range_phones = range(len(phones))
    safe_range_markets = range(len(markets))
    
    # 2. VARIABLES
    # Decision variables: number of phones allocated to each market
    x = {(m, p): mdl.integer_var(name=f"x_{m}_{p}", lb=0) for m in markets for p in phones}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    objective = mdl.sum(prices[p] * x[m, p] for m in markets for p in phones)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Stock Availability Constraint
    for p in phones:
        mdl.add_constraint(mdl.sum(x[m, p] for m in markets) <= available_stock[p], ctname=f"stock_avail_{p}")
    
    # Market Capacity Constraint
    for m in markets:
        mdl.add_constraint(mdl.sum(x[m, p] for p in phones) <= max_stock_capacity[m], ctname=f"market_cap_{m}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for m in markets:
            for p in phones:
                value = solution.get_value(x[m, p])
                if value > 1e-6:
                    print(f"x[{m},{p}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_phone_distribution()