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

from docplex.mp.model import Model

def manufacturing_optimization():
    """Optimize product portfolio to maximize revenue under constraints."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="manufactory_1")
    
    # Data from the problem statement
    prices = [10.5, 15.0, 20.0]
    costs = [2.5, 3.0, 4.0]
    demands = [100, 150, 200]
    capacities = [500, 600, 700]
    budget = 5000  # Predefined budget
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(prices) == len(costs) == len(demands) == len(capacities), "Array length mismatch"
    safe_range = range(min(len(prices), len(costs), len(demands), len(capacities)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: number of units produced for each product
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    revenue = mdl.sum(prices[i] * x[i] for i in safe_range)
    mdl.maximize(revenue)
    
    # 4. CONSTRAINTS
    
    # Total Production Cost Constraint
    total_cost = mdl.sum(costs[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_cost <= budget, ctname="total_cost_constraint")
    
    # Demand Fulfillment Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] >= demands[i], ctname=f"demand_{i}")
    
    # Production Capacity Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] <= capacities[i], ctname=f"capacity_{i}")
    
    # 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])
            print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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