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

import gurobipy as gp
from gurobipy import GRB

def optimize_book_production():
    """Optimize book production to maximize revenue while adhering to constraints."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("book_production_optimization")
    
    # Data from the problem
    n_books = 3
    prices = [20.0, 25.0, 30.0]  # From book_prices.Price
    costs = [10.0, 12.0, 15.0]   # From production_costs.Cost
    min_demand = [500, 600, 700] # From minimum_demand.Min_Demand
    max_issues = 6000            # From max_issues.Max_Issues
    total_budget = 150000        # From total_budget.Total_Budget
    
    # CRITICAL: Validate array lengths before loops
    assert len(prices) == len(costs) == len(min_demand) == n_books, "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables: number of copies produced for each book
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=0) for i in range(n_books)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue: sum of (price * number of copies) for each book
    model.setObjective(gp.quicksum(prices[i] * x[i] for i in range(n_books)), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Production Budget: sum of (cost * number of copies) <= total_budget
    model.addConstr(gp.quicksum(costs[i] * x[i] for i in range(n_books)) <= total_budget, name="total_budget")
    
    # Maximum Issues per Book: number of copies <= max_issues for each book
    for i in range(n_books):
        model.addConstr(x[i] <= max_issues, name=f"max_issues_{i}")
    
    # Minimum Demand: number of copies >= min_demand for each book
    for i in range(n_books):
        model.addConstr(x[i] >= min_demand[i], name=f"min_demand_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_books):
            print(f"x[{i}] = {x[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

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