# Complete GUROBIPY implementation - Retry Attempt 1

import gurobipy as gp
from gurobipy import GRB

def optimize_program_share():
    """Optimize program share allocation across channels using Gurobi."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("program_share")
    
    # Data: Share percentages and maximum share capacities
    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
    }
    
    # Extract unique channels and programs
    channels = set(c for c, p in share_data.keys())
    programs = set(p for c, p in share_data.keys())
    
    # CRITICAL: Validate data consistency
    assert all((c, p) in share_data for c in channels for p in programs if (c, p) in share_data), "Data inconsistency detected"
    
    # 2. VARIABLES
    x = model.addVars(share_data.keys(), vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(share_data[c, p] * x[c, p] for c, p in share_data.keys()), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    # Channel Share Capacity Constraints
    for c in channels:
        model.addConstr(
            gp.quicksum(share_data.get((c, p), 0) * x[c, p] for p in programs if (c, p) in share_data) <= max_share_capacity[c],
            name=f"capacity_{c}"
        )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for c, p in share_data.keys():
            if x[c, p].x > 1e-6:
                print(f"x[{c},{p}] = {x[c, p].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")

# Run the optimization
optimize_program_share()