# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_marketing_budget():
    """Optimize marketing budget allocation across cities to maximize rating improvement."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="restaurant_marketing")
    
    # Coefficients for rating improvement per unit of budget
    coefficients = [0.15, 0.25, 0.10]
    
    # Total marketing budget available
    total_budget = 100000
    
    # Number of cities
    n_cities = len(coefficients)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(coefficients) == n_cities, "Array length mismatch"
    safe_range = range(n_cities)  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries for budget allocations
    allocation = {i: mdl.continuous_var(name=f"allocation_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total expected improvement in restaurant ratings
    objective = mdl.sum(coefficients[i] * allocation[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total budget constraint
    total_allocation = mdl.sum(allocation[i] for i in safe_range)
    mdl.add_constraint(total_allocation <= total_budget, ctname="total_budget_constraint")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(allocation[i])
            if value > 1e-6:
                print(f"allocation[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_marketing_budget()