# Complete PYOMO implementation - Retry Attempt 4

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def film_allocation_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # 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 indexing
    assert len(average_revenues) == n_films * n_markets, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_films)  # Films
    model.J = pyo.RangeSet(1, n_markets)  # Markets
    
    # 4. PARAMETERS (data containers)
    # Initialize average_revenue as a parameter indexed by film and market
    model.average_revenue = pyo.Param(model.I, model.J, initialize=lambda model, i, j: average_revenues[(i-1)*n_markets + (j-1)])
    
    # 5. VARIABLES
    # Decision variable: proportion of film i allocated to market j
    model.x = pyo.Var(model.I, model.J, within=pyo.NonNegativeReals, bounds=(0, 1))
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total gross revenue
    def obj_rule(model):
        return sum(model.average_revenue[i, j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total allocation for each film cannot exceed 100%
    def total_allocation_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= 1
    model.total_allocation_constraint = pyo.Constraint(model.I, rule=total_allocation_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i},{j}] = {x_val:.3f}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

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