# Complete PYOMO implementation

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

def manufactory_optimization():
    """Optimize product portfolio to maximize revenue while adhering to constraints."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define the number of products
    n_products = 3
    
    # Define the 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  # Assume a predefined budget
    
    # CRITICAL: Validate array lengths before indexing
    assert len(prices) == len(costs) == len(demands) == len(capacities) == n_products, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_products)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.price = pyo.Param(model.I, initialize={i+1: prices[i] for i in range(n_products)})
    model.cost = pyo.Param(model.I, initialize={i+1: costs[i] for i in range(n_products)})
    model.demand = pyo.Param(model.I, initialize={i+1: demands[i] for i in range(n_products)})
    model.capacity = pyo.Param(model.I, initialize={i+1: capacities[i] for i in range(n_products)})
    model.budget = pyo.Param(initialize=budget)
    
    # 5. VARIABLES
    # Continuous variables for units produced
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total revenue
    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 Cost Constraint
    def total_cost_rule(model):
        return sum(model.cost[i] * model.x[i] for i in model.I) <= model.budget
    model.total_cost_constraint = pyo.Constraint(rule=total_cost_rule)
    
    # Demand Fulfillment Constraint
    def demand_rule(model, i):
        return model.x[i] >= model.demand[i]
    model.demand_constraint = pyo.Constraint(model.I, rule=demand_rule)
    
    # Production Capacity Constraint
    def capacity_rule(model, i):
        return model.x[i] <= model.capacity[i]
    model.capacity_constraint = pyo.Constraint(model.I, rule=capacity_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("\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__":
    manufactory_optimization()