# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def optimize_tv_schedule():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="tvshow_optimization")
    
    # 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
    minimum_demographic_target = 200000
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(viewers_m) == len(air_time) == len(content_type) == len(demographic_target), "Array length mismatch"
    safe_range = range(len(viewers_m))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(viewers_m[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total Air Time Constraint for Each Channel
    for j, total_time in enumerate(total_available_time):
        mdl.add_constraint(mdl.sum(air_time[i] * x[i] for i in safe_range) <= total_time, ctname=f"total_air_time_channel_{j}")
    
    # Content Type Capacity Constraint for Each Channel
    for j, capacity in enumerate(content_capacity):
        mdl.add_constraint(mdl.sum(x[i] for i in safe_range if content_type[i] == 'series') <= capacity, ctname=f"content_capacity_series_channel_{j}")
        mdl.add_constraint(mdl.sum(x[i] for i in safe_range if content_type[i] == 'cartoon') <= capacity, ctname=f"content_capacity_cartoon_channel_{j}")
    
    # Minimum Demographic Viewership Constraint
    mdl.add_constraint(mdl.sum(demographic_target[i] * x[i] for i in safe_range) >= minimum_demographic_target, ctname="min_demographic_target")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_tv_schedule()