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

import gurobipy as gp
from gurobipy import GRB

def manufacturing_optimization():
    """Optimize product portfolio to maximize revenue while adhering to constraints."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("manufactory_1")
    
    # Data from the problem
    prices = [10.5, 15.0, 20.0]
    costs = [2.5, 3.0, 4.0]
    demands = [100, 150, 200]
    capacities = [500, 600, 700]
    budget = 5000
    
    # Number of products
    n_products = len(prices)
    
    # CRITICAL: Validate array lengths before loops
    assert len(prices) == len(costs) == len(demands) == len(capacities) == n_products, "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables: number of units produced for each product
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=0) for i in range(n_products)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    model.setObjective(gp.quicksum(prices[i] * x[i] for i in range(n_products)), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Production Cost Constraint
    model.addConstr(gp.quicksum(costs[i] * x[i] for i in range(n_products)) <= budget, name="total_cost")
    
    # Demand Fulfillment Constraints
    for i in range(n_products):
        model.addConstr(x[i] >= demands[i], name=f"demand_{i}")
    
    # Production Capacity Constraints
    for i in range(n_products):
        model.addConstr(x[i] <= capacities[i], name=f"capacity_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_products):
            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

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