# Complete PYOMO implementation

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

def film_rank_optimization():
    """Film distribution optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided 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 unique film-market pairs
    films = set(film_id for film_id, _, _ in film_market_data)
    markets = set(market_id for _, market_id, _ in film_market_data)
    
    # 3. SETS
    model.F = pyo.Set(initialize=films)
    model.M = pyo.Set(initialize=markets)
    model.FM = pyo.Set(initialize=[(f, m) for f, m, _ in film_market_data])
    
    # 4. PARAMETERS
    low_estimate_dict = {(f, m): low for f, m, low in film_market_data}
    model.Low_Estimate = pyo.Param(model.FM, initialize=low_estimate_dict)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.FM, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Low_Estimate[f, m] * model.x[f, m] for f, m in model.FM)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def budget_constraint_rule(model):
        return sum(model.Low_Estimate[f, m] * model.x[f, m] for f, m in model.FM) <= B
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_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)}")
        
        # Extract variable values
        print("\nVariable values:")
        for f, m in model.FM:
            x_val = pyo.value(model.x[f, m])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{f},{m}] = {int(x_val)}")
        
    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
film_rank_optimization()