#!/usr/bin/env python3
"""
DOCplex implementation for wine production optimization problem
"""

from docplex.mp.model import Model

def wine_production_optimization():
    """Optimize wine production to maximize profit"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="wine_production_optimization")
    
    # Data from the problem
    profits = [10.5, 15.0, 20.0]
    grape_usages = [2.5, 3.0, 4.0]
    production_costs = [5.0, 6.0, 7.0]
    market_demands = [100, 150, 200]
    total_budget = 100000
    total_grapes_available = 1000  # Assuming a value for total grapes available
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(profits) == len(grape_usages) == len(production_costs) == len(market_demands), "Array length mismatch"
    safe_range = range(min(len(profits), len(grape_usages), len(production_costs), len(market_demands)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: number of cases to produce for each wine type
    x = {i: mdl.integer_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total profit
    objective = mdl.sum(profits[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Grape availability constraint
    grape_usage = mdl.sum(grape_usages[i] * x[i] for i in safe_range)
    mdl.add_constraint(grape_usage <= total_grapes_available, ctname="grape_availability")
    
    # Production budget constraint
    total_cost = mdl.sum(production_costs[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_cost <= total_budget, ctname="production_budget")
    
    # 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])
            print(f"x[{i}] = {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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