#!/usr/bin/env python3
"""
DOCPLEX Implementation for Furniture Manufacturer Optimization Problem
"""

from docplex.mp.model import Model

def furniture_optimization():
    """Optimize furniture production to maximize profit."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="furniture_optimization")
    
    # Data from the problem
    furniture_ids = [1, 2, 3]
    market_rates = [120.0, 180.0, 250.0]
    production_costs = [60.0, 90.0, 130.0]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(furniture_ids) == len(market_rates) == len(production_costs), "Array length mismatch"
    safe_range = range(min(len(furniture_ids), len(market_rates), len(production_costs)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: Number of units produced for each furniture type
    x = {i: mdl.continuous_var(name=f"x_{furniture_ids[i]}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total profit: sum((Market_Rate - Price_in_Dollar) * Quantity_Produced)
    profit_coefficients = [market_rates[i] - production_costs[i] for i in safe_range]
    objective = mdl.sum(profit_coefficients[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Production Capacity: sum(Quantity_Produced) <= 1000
    total_production = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_production <= 1000, ctname="total_production_capacity")
    
    # Budget Limit: sum(Price_in_Dollar * Quantity_Produced) <= 50000
    total_cost = mdl.sum(production_costs[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_cost <= 50000, ctname="budget_limit")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{furniture_ids[i]}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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