# Complete PYOMO implementation - Retry Attempt 4

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

def program_share_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define sets
    channels = [1, 2, 3]
    programs = [1, 2, 3]
    time_slots = [1, 2, 3]
    
    # Define parameters
    program_shares = {
        (1, 1): 60,
        (2, 2): 70,
        (3, 3): 50
    }
    
    channel_ratings = {
        1: 75,
        2: 85,
        3: 80
    }
    
    program_origins = {
        1: 'Local',
        2: 'International',
        3: 'Local'
    }
    
    # Validate array lengths
    assert len(program_shares) == len(programs) * len(channels), "Program shares length mismatch"
    assert len(channel_ratings) == len(channels), "Channel ratings length mismatch"
    assert len(program_origins) == len(programs), "Program origins length mismatch"
    
    # 3. SETS
    model.C = pyo.Set(initialize=channels)
    model.P = pyo.Set(initialize=programs)
    model.T = pyo.Set(initialize=time_slots)
    
    # 4. PARAMETERS
    model.program_shares = pyo.Param(model.C, model.P, initialize=program_shares)
    model.channel_ratings = pyo.Param(model.C, initialize=channel_ratings)
    model.program_origins = pyo.Param(model.P, initialize=program_origins)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.C, model.P, model.T, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.program_shares[c, p] * model.channel_ratings[c] * model.x[c, p, t] for c in model.C for p in model.P for t in model.T)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Program Uniqueness
    def program_uniqueness_rule(model, p):
        return sum(model.x[c, p, t] for c in model.C for t in model.T) <= 1
    model.program_uniqueness = pyo.Constraint(model.P, rule=program_uniqueness_rule)
    
    # Channel Time Slot Limit
    def channel_time_slot_limit_rule(model, c):
        return sum(model.x[c, p, t] for p in model.P for t in model.T) <= 5
    model.channel_time_slot_limit = pyo.Constraint(model.C, rule=channel_time_slot_limit_rule)
    
    # Local Program Requirement
    def local_program_requirement_rule(model, c):
        return sum(model.x[c, p, t] for p in model.P if model.program_origins[p] == 'Local' for t in model.T) >= 2
    model.local_program_requirement = pyo.Constraint(model.C, rule=local_program_requirement_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 c in model.C:
            for p in model.P:
                for t in model.T:
                    if pyo.value(model.x[c, p, t]) > 0:
                        print(f"x[{c}, {p}, {t}] = {pyo.value(model.x[c, p, t])}")
        
    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__":
    program_share_optimization()