# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_wine_production():
    """Optimize wine production to maximize revenue"""

    # 1. MODEL & DATA SETUP
    mdl = Model(name="wine_optimization")
    
    # Data from the problem statement
    prices = [12.0, 18.0, 22.0]
    market_demands = [500, 800, 300]
    total_production_capacity = 500
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(prices) == len(market_demands), "Array length mismatch"
    safe_range = range(min(len(prices), len(market_demands)))  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries (most common)
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Use mdl.sum() for summations (DOCplex specific)
    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_production_capacity, ctname="total_capacity")
    
    # Market demand constraints
    for i in safe_range:
        mdl.add_constraint(x[i] <= market_demands[i], ctname=f"market_demand_{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])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_wine_production()