# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def film_revenue_optimization():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="film_revenue_optimization")
    
    # Data from the database
    average_revenues = [400000.0, 550000.0, 250000.0, 475000.0, 325000.0]
    n_films = 2
    n_markets = 3
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(average_revenues) == n_films * n_markets, "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables: x_{ij} represents the proportion of film i allocated to market j
    x = {(i, j): mdl.continuous_var(name=f"x_{i}_{j}", lb=0) 
         for i in range(n_films) for j in range(n_markets)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total gross revenue
    objective = mdl.sum(average_revenues[i * n_markets + j] * x[(i, j)] 
                        for i in range(n_films) for j in range(n_markets))
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Total allocation for each film cannot exceed 100%
    for i in range(n_films):
        total_allocation = mdl.sum(x[(i, j)] for j in range(n_markets))
        mdl.add_constraint(total_allocation <= 1, ctname=f"total_allocation_film_{i}")
    
    # Non-negative allocation proportions (already handled by lb=0 in variable definition)
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in range(n_films):
            for j in range(n_markets):
                value = solution.get_value(x[(i, j)])
                if value > 1e-6:
                    print(f"x_{i}_{j} = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
film_revenue_optimization()