# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_production():
    """Optimize production quantities to maximize revenue"""

    # 1. MODEL & DATA SETUP
    mdl = Model(name="manufactory_1")
    
    # Data from the problem context
    prices = [12.99, 18.49, 22.00]
    capacities = [5000, 7000, 8000]
    total_capacity = sum(capacities)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(prices) == len(capacities) == 3, "Array length mismatch"
    safe_range = range(min(len(prices), len(capacities)))  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries for production quantities
    x = {i: mdl.continuous_var(name=f"x_{i+1}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    objective = mdl.sum(prices[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total production capacity constraint
    total_production = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_production <= total_capacity, ctname="total_capacity")
    
    # Manufacturer-specific capacity constraints
    for i in safe_range:
        mdl.add_constraint(x[i] <= capacities[i], ctname=f"capacity_{i+1}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value:.2f}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i+1}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_production()