# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def optimize_tv_schedule():
    """Optimize TV schedule to maximize viewership."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("tvshow")
    
    # Data from the problem statement
    viewers_m = [2, 3, 1]
    air_time = [60, 90, 30]
    content_type = ['series', 'cartoon', 'series']
    demographic_target = [80000, 120000, 50000]
    
    total_available_time = [48, 72, 24]
    content_capacity = [20, 30, 10]
    
    minimum_demographic_target = 200000
    
    n_shows = len(viewers_m)
    n_channels = len(total_available_time)
    
    # CRITICAL: Validate array lengths before loops
    assert len(viewers_m) == len(air_time) == len(content_type) == len(demographic_target) == n_shows, "Array length mismatch"
    assert len(total_available_time) == len(content_capacity) == n_channels, "Channel array length mismatch"
    
    # 2. VARIABLES
    x = model.addVars(n_shows, vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(viewers_m[i] * x[i] for i in range(n_shows)), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Air Time Constraint for Each Channel
    for j in range(n_channels):
        model.addConstr(gp.quicksum(air_time[i] * x[i] for i in range(n_shows)) <= total_available_time[j], name=f"air_time_channel_{j}")
    
    # Content Type Capacity Constraint for Each Channel
    for j in range(n_channels):
        model.addConstr(gp.quicksum(x[i] for i in range(n_shows) if content_type[i] == 'series') <= content_capacity[j], name=f"content_capacity_series_channel_{j}")
        model.addConstr(gp.quicksum(x[i] for i in range(n_shows) if content_type[i] == 'cartoon') <= content_capacity[j], name=f"content_capacity_cartoon_channel_{j}")
    
    # Minimum Demographic Viewership Constraint
    model.addConstr(gp.quicksum(demographic_target[i] * x[i] for i in range(n_shows)) >= minimum_demographic_target, name="min_demographic_target")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_shows):
            if x[i].x > 1e-6:
                print(f"Show {i} selected: x[{i}] = {x[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_tv_schedule()