# Complete PYOMO implementation

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

def culture_company_optimization():
    """Optimize investment in book clubs and movies to maximize cultural impact."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Coefficients for the objective function
    book_club_coeffs = [0.6, 0.8, 0.5]
    movie_coeffs = [0.7, 0.9, 0.4]
    
    # Budget constraint
    budget_constraint = 1000000
    
    # Validate array lengths
    n_book_clubs = len(book_club_coeffs)
    n_movies = len(movie_coeffs)
    assert n_book_clubs == 3 and n_movies == 3, "Array length mismatch for coefficients"
    
    # 3. SETS
    model.B = pyo.RangeSet(1, n_book_clubs)  # Book clubs
    model.M = pyo.RangeSet(1, n_movies)      # Movies
    
    # 4. PARAMETERS
    model.book_club_coeff = pyo.Param(model.B, initialize={i+1: book_club_coeffs[i] for i in range(n_book_clubs)})
    model.movie_coeff = pyo.Param(model.M, initialize={i+1: movie_coeffs[i] for i in range(n_movies)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.B, within=pyo.NonNegativeReals)  # Investment in book clubs
    model.y = pyo.Var(model.M, within=pyo.NonNegativeReals)  # Investment in movies
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.book_club_coeff[i] * model.x[i] for i in model.B) + \
               sum(model.movie_coeff[j] * model.y[j] for j in model.M)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def budget_rule(model):
        return sum(model.x[i] for i in model.B) + sum(model.y[j] for j in model.M) <= budget_constraint
    model.budget_constraint = pyo.Constraint(rule=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("\nInvestment values:")
        for i in model.B:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"Investment in book club {i}: {x_val:.3f}")
        
        for j in model.M:
            y_val = pyo.value(model.y[j])
            if y_val > 1e-6:  # Only print non-zero values
                print(f"Investment in movie {j}: {y_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

# Run the optimization
culture_company_optimization()