# Complete DOCPLEX implementation

from docplex.mp.model import Model

def film_rank_optimization():
    """Film distribution optimization using DOCPLEX"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="film_rank")
    
    # Data from the problem context
    film_market_data = [
        (1, 101, 12000.0),
        (1, 102, 15000.0),
        (2, 101, 8000.0),
        (2, 103, 20000.0),
        (3, 102, 25000.0)
    ]
    
    # Budget limit
    B = 50000.0  # Example budget limit
    
    # Extracting data into separate lists for safety
    film_ids = [data[0] for data in film_market_data]
    market_ids = [data[1] for data in film_market_data]
    low_estimates = [data[2] for data in film_market_data]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(film_ids) == len(market_ids) == len(low_estimates), "Array length mismatch"
    safe_range = range(len(film_market_data))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for film distribution
    x = {(film_ids[i], market_ids[i]): mdl.binary_var(name=f"x_{film_ids[i]}_{market_ids[i]}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total gross revenue
    objective = mdl.sum(low_estimates[i] * x[(film_ids[i], market_ids[i])] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Budget constraint
    total_revenue = mdl.sum(low_estimates[i] * x[(film_ids[i], market_ids[i])] for i in safe_range)
    mdl.add_constraint(total_revenue <= B, ctname="budget_limit")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            film_id = film_ids[i]
            market_id = market_ids[i]
            value = solution.get_value(x[(film_id, market_id)])
            if value > 1e-6:
                print(f"x[{film_id}, {market_id}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
film_rank_optimization()