#!/usr/bin/env python3
"""
DOCplex implementation for TV show optimization problem
"""

from docplex.mp.model import Model

def tvshow_optimization():
    """Optimize TV show and cartoon airtime allocation to maximize viewer ratings."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="tvshow_optimization")
    
    # Data from the problem statement
    tv_series_ratings = [4.8, 4.3, 4.6]
    cartoon_ratings = [4.5, 4.1, 4.4]
    
    tv_series_min_episodes = [2, 1, 3]
    tv_series_max_episodes = [8, 6, 7]
    
    cartoon_min_episodes = [1, 2, 1]
    cartoon_max_episodes = [5, 4, 6]
    
    diversity_scores = [15, 10, 20]
    
    total_airtime = 1200
    min_diversity = 50
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(tv_series_ratings) == len(tv_series_min_episodes) == len(tv_series_max_episodes) == len(diversity_scores), "TV series array length mismatch"
    assert len(cartoon_ratings) == len(cartoon_min_episodes) == len(cartoon_max_episodes) == len(diversity_scores), "Cartoon array length mismatch"
    
    safe_range_tv = range(len(tv_series_ratings))
    safe_range_cartoon = range(len(cartoon_ratings))
    
    # 2. VARIABLES
    x = {i: mdl.integer_var(name=f"x_{i}", lb=tv_series_min_episodes[i], ub=tv_series_max_episodes[i]) for i in safe_range_tv}
    y = {i: mdl.integer_var(name=f"y_{i}", lb=cartoon_min_episodes[i], ub=cartoon_max_episodes[i]) for i in safe_range_cartoon}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(tv_series_ratings[i] * x[i] for i in safe_range_tv) + \
               mdl.sum(cartoon_ratings[i] * y[i] for i in safe_range_cartoon)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Airtime Constraint
    total_airtime_expr = mdl.sum(x[i] for i in safe_range_tv) + \
                         mdl.sum(y[i] for i in safe_range_cartoon)
    mdl.add_constraint(total_airtime_expr <= total_airtime, ctname="total_airtime")
    
    # Diversity Constraint
    diversity_expr = mdl.sum(diversity_scores[i] * x[i] for i in safe_range_tv) + \
                     mdl.sum(diversity_scores[i] * y[i] for i in safe_range_cartoon)
    mdl.add_constraint(diversity_expr >= min_diversity, ctname="diversity")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range_tv:
            value = solution.get_value(x[i])
            print(f"TV Series {i+1} episodes aired: {value}")
        for i in safe_range_cartoon:
            value = solution.get_value(y[i])
            print(f"Cartoon {i+1} episodes aired: {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
if __name__ == "__main__":
    tvshow_optimization()