# Complete PYOMO implementation

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

def optimize_production():
    """Optimize production quantities to maximize revenue"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Prices and capacities from the database
    prices = [12.99, 18.49, 22.00]
    capacities = [5000, 7000, 8000]
    total_capacity = sum(capacities)
    
    # CRITICAL: Validate array lengths before indexing
    n_products = len(prices)
    assert len(capacities) == n_products, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_products)  # 1-based indexing
    
    # 4. PARAMETERS
    model.price = pyo.Param(model.I, initialize={i+1: prices[i] for i in range(n_products)})
    model.capacity = pyo.Param(model.I, initialize={i+1: capacities[i] for i in range(n_products)})
    
    # 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 capacity constraint
    def total_capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= total_capacity
    model.total_capacity_constraint = pyo.Constraint(rule=total_capacity_rule)
    
    # Manufacturer-specific capacity constraints
    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):.2f}")
        
        # 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

# Run the optimization
optimize_production()