#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for TV Show Optimization Problem
"""

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def tvshow_optimization():
    """Optimize TV show episode allocation to maximize viewer ratings."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # TV Series Data
    tv_series_ratings = [4.8, 4.3, 4.6]
    tv_series_min_episodes = [2, 1, 3]
    tv_series_max_episodes = [8, 6, 7]
    tv_series_diversity_scores = [15, 10, 20]
    
    # Cartoon Data
    cartoon_ratings = [4.5, 4.1, 4.4]
    cartoon_min_episodes = [1, 2, 1]
    cartoon_max_episodes = [5, 4, 6]
    cartoon_diversity_scores = [15, 10, 20]
    
    # Validate array lengths
    assert len(tv_series_ratings) == len(tv_series_min_episodes) == len(tv_series_max_episodes) == len(tv_series_diversity_scores), "TV Series data length mismatch"
    assert len(cartoon_ratings) == len(cartoon_min_episodes) == len(cartoon_max_episodes) == len(cartoon_diversity_scores), "Cartoon data length mismatch"
    
    # 3. SETS
    model.TV = pyo.RangeSet(1, len(tv_series_ratings))  # 1-based indexing for TV series
    model.CARTOON = pyo.RangeSet(1, len(cartoon_ratings))  # 1-based indexing for cartoons
    
    # 4. PARAMETERS
    model.tv_rating = pyo.Param(model.TV, initialize={i+1: tv_series_ratings[i] for i in range(len(tv_series_ratings))})
    model.tv_min_episodes = pyo.Param(model.TV, initialize={i+1: tv_series_min_episodes[i] for i in range(len(tv_series_min_episodes))})
    model.tv_max_episodes = pyo.Param(model.TV, initialize={i+1: tv_series_max_episodes[i] for i in range(len(tv_series_max_episodes))})
    model.tv_diversity = pyo.Param(model.TV, initialize={i+1: tv_series_diversity_scores[i] for i in range(len(tv_series_diversity_scores))})
    
    model.cartoon_rating = pyo.Param(model.CARTOON, initialize={i+1: cartoon_ratings[i] for i in range(len(cartoon_ratings))})
    model.cartoon_min_episodes = pyo.Param(model.CARTOON, initialize={i+1: cartoon_min_episodes[i] for i in range(len(cartoon_min_episodes))})
    model.cartoon_max_episodes = pyo.Param(model.CARTOON, initialize={i+1: cartoon_max_episodes[i] for i in range(len(cartoon_max_episodes))})
    model.cartoon_diversity = pyo.Param(model.CARTOON, initialize={i+1: cartoon_diversity_scores[i] for i in range(len(cartoon_diversity_scores))})
    
    # 5. VARIABLES
    model.tv_episodes = pyo.Var(model.TV, within=pyo.NonNegativeIntegers)
    model.cartoon_episodes = pyo.Var(model.CARTOON, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.tv_rating[i] * model.tv_episodes[i] for i in model.TV) + \
               sum(model.cartoon_rating[j] * model.cartoon_episodes[j] for j in model.CARTOON)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total Airtime Constraint
    def airtime_rule(model):
        return sum(model.tv_episodes[i] for i in model.TV) + \
               sum(model.cartoon_episodes[j] for j in model.CARTOON) <= 1200
    model.airtime_constraint = pyo.Constraint(rule=airtime_rule)
    
    # Episode Bounds Constraint for TV Series
    def tv_episode_bounds_rule(model, i):
        return (model.tv_min_episodes[i], model.tv_episodes[i], model.tv_max_episodes[i])
    model.tv_episode_bounds = pyo.Constraint(model.TV, rule=tv_episode_bounds_rule)
    
    # Episode Bounds Constraint for Cartoons
    def cartoon_episode_bounds_rule(model, j):
        return (model.cartoon_min_episodes[j], model.cartoon_episodes[j], model.cartoon_max_episodes[j])
    model.cartoon_episode_bounds = pyo.Constraint(model.CARTOON, rule=cartoon_episode_bounds_rule)
    
    # Diversity Constraint
    def diversity_rule(model):
        return sum(model.tv_diversity[i] * model.tv_episodes[i] for i in model.TV) + \
               sum(model.cartoon_diversity[j] * model.cartoon_episodes[j] for j in model.CARTOON) >= 50
    model.diversity_constraint = pyo.Constraint(rule=diversity_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nTV Series Episodes:")
        for i in model.TV:
            print(f"TV Series {i}: {pyo.value(model.tv_episodes[i])}")
        
        print("\nCartoon Episodes:")
        for j in model.CARTOON:
            print(f"Cartoon {j}: {pyo.value(model.cartoon_episodes[j])}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

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