# Complete PYOMO implementation

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

def book_optimization():
    """Optimization for maximizing revenue from book publications"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    n_books = 3
    prices = [18.99, 22.5, 14.75]
    max_issues = 50  # Example maximum number of issues allowed
    total_budget = 1000  # Example total budget available
    
    # CRITICAL: Validate array lengths before indexing
    assert len(prices) == n_books, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.B = pyo.RangeSet(1, n_books)  # 1-based indexing for books
    
    # 4. PARAMETERS (data containers)
    model.price = pyo.Param(model.B, initialize={i+1: prices[i] for i in range(n_books)})
    
    # 5. VARIABLES
    # Integer variables for number of issues
    model.x = pyo.Var(model.B, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.price[i] * model.x[i] for i in model.B)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total number of issues constraint
    def total_issues_rule(model):
        return sum(model.x[i] for i in model.B) <= max_issues
    model.total_issues_constraint = pyo.Constraint(rule=total_issues_rule)
    
    # Budget constraint
    def budget_rule(model):
        return sum(model.price[i] * model.x[i] for i in model.B) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_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.B:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.0f}")
        
    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

# Run the optimization
book_optimization()