# Complete PYOMO implementation - Retry Attempt 1

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

def program_share_optimization():
    """Optimize program allocation across channels to maximize share percentage."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem description
    channels = [1, 2, 3]
    programs = [101, 102, 103]
    share_data = {
        (1, 101): 12.5,
        (1, 102): 18.0,
        (2, 103): 15.0,
        (2, 101): 10.0,
        (3, 102): 20.0
    }
    max_share_capacity = {
        1: 30.0,
        2: 25.0,
        3: 20.0
    }
    
    # 3. SETS
    model.C = pyo.Set(initialize=channels)
    model.P = pyo.Set(initialize=programs)
    model.CP = pyo.Set(initialize=share_data.keys(), dimen=2)
    
    # 4. PARAMETERS
    model.Share_in_percent = pyo.Param(model.CP, initialize=share_data)
    model.Max_Share_Capacity = pyo.Param(model.C, initialize=max_share_capacity)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.CP, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Share_in_percent[c, p] * model.x[c, p] for c, p in model.CP)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def channel_capacity_rule(model, c):
        return sum(model.Share_in_percent[c, p] * model.x[c, p] for p in model.P if (c, p) in model.CP) <= model.Max_Share_Capacity[c]
    model.channel_capacity_constraint = pyo.Constraint(model.C, rule=channel_capacity_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    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, p in model.CP:
            x_val = pyo.value(model.x[c, p])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{c}, {p}] = {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

# Execute the optimization
program_share_optimization()