# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def film_allocation_optimization():
    # 1. MODEL & DATA SETUP
    model = gp.Model("film_allocation")
    
    # Number of films and markets
    n_films = 2
    n_markets = 3
    
    # Average revenue data
    average_revenues = [400000.0, 550000.0, 250000.0, 475000.0, 325000.0]
    
    # CRITICAL: Validate array lengths before loops
    assert len(average_revenues) == n_films * n_markets, "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables: proportion of film i allocated to market j
    x = model.addVars(n_films, n_markets, vtype=GRB.CONTINUOUS, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total gross revenue
    model.setObjective(
        gp.quicksum(average_revenues[i * n_markets + j] * x[i, j] 
                    for i in range(n_films) for j in range(n_markets)), 
        GRB.MAXIMIZE
    )
    
    # 4. CONSTRAINTS
    # Total allocation for each film cannot exceed 100%
    for i in range(n_films):
        model.addConstr(
            gp.quicksum(x[i, j] for j in range(n_markets)) <= 1, 
            name=f"total_allocation_film_{i}"
        )
    
    # Non-negative allocation proportions (already handled by lb=0 in addVars)
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_films):
            for j in range(n_markets):
                if x[i, j].x > 1e-6:
                    print(f"x[{i},{j}] = {x[i, j].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
film_allocation_optimization()