# Complete PYOMO implementation

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

def movie_promotion_optimization():
    """Optimize promotional budget allocation for movies"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    n_movies = 3
    sensitivity_values = [0.15, 0.25, 0.1]
    min_budgets = [20000, 30000, 15000]
    total_budget = 65000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(sensitivity_values) == len(min_budgets) == n_movies, "Array length mismatch"
    
    # 3. SETS
    model.M = pyo.RangeSet(1, n_movies)  # 1-based indexing for movies
    
    # 4. PARAMETERS
    model.sensitivity = pyo.Param(model.M, initialize={i+1: sensitivity_values[i] for i in range(n_movies)})
    model.min_budget = pyo.Param(model.M, initialize={i+1: min_budgets[i] for i in range(n_movies)})
    
    # 5. VARIABLES
    model.budget_allocation = pyo.Var(model.M, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.sensitivity[m] * model.budget_allocation[m] for m in model.M)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total budget constraint
    def total_budget_rule(model):
        return sum(model.budget_allocation[m] for m in model.M) <= total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    # Minimum budget constraints for each movie
    def min_budget_rule(model, m):
        return model.budget_allocation[m] >= model.min_budget[m]
    model.min_budget_constraints = pyo.Constraint(model.M, rule=min_budget_rule)
    
    # 8. SOLVING WITH GUROBI
    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):.3f}")
        
        # Extract variable values
        print("\nBudget Allocation:")
        for m in model.M:
            allocation_val = pyo.value(model.budget_allocation[m])
            print(f"Movie {m}: {allocation_val:.2f}")
        
    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

# Run the optimization
movie_promotion_optimization()