# Complete PYOMO implementation

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

def music_optimization():
    """Optimize song storage for a music streaming service"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Song data
    ratings = [4.5, 3.8, 5.0]
    file_sizes = [5000, 3000, 7000]
    resolutions = [1080, 720, 480]
    
    # Business constraints
    total_storage_capacity = 10000
    minimum_resolution_quality = 1500
    
    # Validate array lengths
    n_songs = len(ratings)
    assert len(file_sizes) == len(resolutions) == n_songs, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_songs)  # 1-based indexing
    
    # 4. PARAMETERS
    model.rating = pyo.Param(model.I, initialize={i+1: ratings[i] for i in range(n_songs)})
    model.file_size = pyo.Param(model.I, initialize={i+1: file_sizes[i] for i in range(n_songs)})
    model.resolution = pyo.Param(model.I, initialize={i+1: resolutions[i] for i in range(n_songs)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.rating[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def storage_capacity_rule(model):
        return sum(model.file_size[i] * model.x[i] for i in model.I) <= total_storage_capacity
    model.storage_capacity_constraint = pyo.Constraint(rule=storage_capacity_rule)
    
    def resolution_quality_rule(model):
        return sum(model.resolution[i] * model.x[i] for i in model.I) >= minimum_resolution_quality
    model.resolution_quality_constraint = pyo.Constraint(rule=resolution_quality_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 i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {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
music_optimization()