# Complete PYOMO implementation

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

def furniture_optimization():
    """Pyomo implementation for furniture manufacturer optimization problem."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    furniture_ids = [1, 2, 3]
    market_rates = {1: 120.0, 2: 180.0, 3: 250.0}
    production_costs = {1: 60.0, 2: 90.0, 3: 130.0}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(furniture_ids) == len(market_rates) == len(production_costs), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=furniture_ids)  # Furniture types
    
    # 4. PARAMETERS (data containers)
    model.market_rate = pyo.Param(model.I, initialize=market_rates)
    model.production_cost = pyo.Param(model.I, initialize=production_costs)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)  # Units produced
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((model.market_rate[i] - model.production_cost[i]) * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total Production Capacity
    def capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= 1000
    model.capacity_constraint = pyo.Constraint(rule=capacity_rule)
    
    # Budget Limit
    def budget_rule(model):
        return sum(model.production_cost[i] * model.x[i] for i in model.I) <= 50000
    model.budget_constraint = pyo.Constraint(rule=budget_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("\nProduction quantities:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"Furniture {i}: {x_val:.0f} units")
        
    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__":
    furniture_optimization()