#!/usr/bin/env python3
"""
DOCPLEX implementation for restaurant placement optimization
"""

from docplex.mp.model import Model

def restaurant_optimization():
    """Optimize restaurant placement to maximize customer satisfaction"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="restaurant_placement")
    
    # Data from the problem
    ratings = [4.5, 3.8, 4.2, 3.9, 4.1]
    regions = ['North', 'South', 'East', 'West', 'North']
    n_cities = len(ratings)
    
    # CRITICAL: Validate array lengths
    assert len(ratings) == len(regions) == n_cities, "Array length mismatch"
    safe_range = range(min(len(ratings), len(regions)))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for each city
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total customer satisfaction
    objective = mdl.sum(ratings[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total budget constraint: No more than 5 new restaurants
    total_restaurants = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_restaurants <= 5, ctname="total_budget")
    
    # Regional distribution constraint: At least 1 restaurant per region
    unique_regions = set(regions)
    for region in unique_regions:
        region_restaurants = mdl.sum(x[i] for i in safe_range if regions[i] == region)
        mdl.add_constraint(region_restaurants >= 1, ctname=f"region_{region}")
    
    # City-level placement constraint: No more than 2 restaurants per city
    for i in safe_range:
        mdl.add_constraint(x[i] <= 2, ctname=f"city_limit_{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

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