# Complete DOCPLEX implementation

from docplex.mp.model import Model

def furniture_optimization():
    """Optimize furniture production and sales for maximum profit."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="furniture_optimization")
    
    # Data: Market rates, production costs, and initial quantities
    market_rates = [120.0, 180.0, 140.0]
    production_costs = [60.0, 90.0, 70.0]
    initial_quantities = [15, 10, 20]
    
    # Constants for capacity constraints
    total_production_capacity = 50  # Example value for P
    total_sales_capacity = 50       # Example value for S
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(market_rates) == len(production_costs) == len(initial_quantities), "Array length mismatch"
    safe_range = range(min(len(market_rates), len(production_costs), len(initial_quantities)))  # Safe indexing
    
    # 2. VARIABLES
    # Integer variables for quantities of each furniture item
    quantities = {i: mdl.integer_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total profit
    profit_margins = [market_rates[i] - production_costs[i] for i in safe_range]
    objective = mdl.sum(profit_margins[i] * quantities[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Total production capacity constraint
    total_production = mdl.sum(quantities[i] for i in safe_range)
    mdl.add_constraint(total_production <= total_production_capacity, ctname="production_capacity")
    
    # Total sales capacity constraint
    total_sales = mdl.sum(quantities[i] for i in safe_range)
    mdl.add_constraint(total_sales <= total_sales_capacity, ctname="sales_capacity")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(quantities[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
furniture_optimization()