#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Phone Market Optimization
"""

import gurobipy as gp
from gurobipy import GRB

def phone_market_optimization():
    """Optimize phone stock allocation across markets to maximize revenue."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("phone_market")
    
    # Data from the problem
    phone_ids = [1, 2, 3]
    market_ids = [1, 2, 3]
    
    prices = {1: 699.99, 2: 899.99, 3: 999.99}
    max_capacities = {1: 1000, 2: 1500, 3: 2000}
    min_stocks = {(1, 1): 50, (2, 2): 100, (3, 3): 150}
    
    # CRITICAL: Validate array lengths before loops
    assert len(phone_ids) == len(prices), "Phone IDs and prices length mismatch"
    assert len(market_ids) == len(max_capacities), "Market IDs and max capacities length mismatch"
    
    # 2. VARIABLES
    x = model.addVars(phone_ids, market_ids, vtype=GRB.INTEGER, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(
        gp.quicksum(prices[i] * x[i, j] for i in phone_ids for j in market_ids),
        GRB.MAXIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Market Capacity Constraint
    for j in market_ids:
        model.addConstr(
            gp.quicksum(x[i, j] for i in phone_ids) <= max_capacities[j],
            name=f"market_capacity_{j}"
        )
    
    # Minimum Stock Requirement Constraint
    for i, j in min_stocks.keys():
        model.addConstr(
            x[i, j] >= min_stocks[(i, j)],
            name=f"min_stock_{i}_{j}"
        )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in phone_ids:
            for j in market_ids:
                if x[i, j].x > 1e-6:
                    print(f"x[{i},{j}] = {x[i, j].x:.0f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
if __name__ == "__main__":
    phone_market_optimization()