#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for TV Show Optimization Problem
"""

import gurobipy as gp
from gurobipy import GRB

def tvshow_optimization():
    """Optimize TV show and cartoon airtime allocation to maximize viewer ratings."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("tvshow_optimization")
    
    # Data from the problem
    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 before loops
    assert len(tv_series_ratings) == len(tv_series_min_episodes) == len(tv_series_max_episodes) == 3, "TV series data length mismatch"
    assert len(cartoon_ratings) == len(cartoon_min_episodes) == len(cartoon_max_episodes) == 3, "Cartoon data length mismatch"
    assert len(diversity_scores) == 3, "Diversity scores length mismatch"
    
    # 2. VARIABLES
    # Decision variables for TV series and cartoons
    x = {i: model.addVar(vtype=GRB.INTEGER, name=f"x_{i}", lb=tv_series_min_episodes[i], ub=tv_series_max_episodes[i]) 
         for i in range(3)}
    
    y = {i: model.addVar(vtype=GRB.INTEGER, name=f"y_{i}", lb=cartoon_min_episodes[i], ub=cartoon_max_episodes[i]) 
         for i in range(3)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total viewer ratings
    model.setObjective(
        gp.quicksum(tv_series_ratings[i] * x[i] for i in range(3)) +
        gp.quicksum(cartoon_ratings[i] * y[i] for i in range(3)),
        GRB.MAXIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Total Airtime Constraint
    model.addConstr(
        gp.quicksum(x[i] for i in range(3)) + gp.quicksum(y[i] for i in range(3)) <= total_airtime,
        name="total_airtime"
    )
    
    # Diversity Constraint
    model.addConstr(
        gp.quicksum(diversity_scores[i] * x[i] for i in range(3)) +
        gp.quicksum(diversity_scores[i] * y[i] for i in range(3)) >= min_diversity,
        name="min_diversity"
    )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(3):
            print(f"TV Series {i+1} episodes aired: {x[i].x}")
        for i in range(3):
            print(f"Cartoon {i+1} episodes aired: {y[i].x}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

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