#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Book Production Optimization Problem
"""

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

def book_production_optimization():
    """Optimize book production to maximize revenue while adhering to constraints."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define the number of books
    n_books = 3
    
    # Data from the problem
    book_prices = [20.0, 25.0, 30.0]
    production_costs = [10.0, 12.0, 15.0]
    min_demand = [500, 600, 700]
    max_issues = [6000, 6000, 6000]
    total_budget = 150000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(book_prices) == len(production_costs) == len(min_demand) == len(max_issues) == n_books, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_books)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.price = pyo.Param(model.I, initialize={i+1: book_prices[i] for i in range(n_books)})
    model.cost = pyo.Param(model.I, initialize={i+1: production_costs[i] for i in range(n_books)})
    model.min_demand = pyo.Param(model.I, initialize={i+1: min_demand[i] for i in range(n_books)})
    model.max_issues = pyo.Param(model.I, initialize={i+1: max_issues[i] for i in range(n_books)})
    model.total_budget = pyo.Param(initialize=total_budget)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.price[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Production Budget Constraint
    def budget_rule(model):
        return sum(model.cost[i] * model.x[i] for i in model.I) <= model.total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Maximum Issues per Book Constraint
    def max_issues_rule(model, i):
        return model.x[i] <= model.max_issues[i]
    model.max_issues_constraint = pyo.Constraint(model.I, rule=max_issues_rule)
    
    # Minimum Demand Constraint
    def min_demand_rule(model, i):
        return model.x[i] >= model.min_demand[i]
    model.min_demand_constraint = pyo.Constraint(model.I, rule=min_demand_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")
        
    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__":
    book_production_optimization()