# Complete PYOMO implementation

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

def furniture_optimization():
    """Optimize furniture production and sales for maximum profit"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Given data for the problem
    market_rates = [120.0, 180.0, 140.0]
    production_costs = [60.0, 90.0, 70.0]
    n_items = len(market_rates)
    
    # Constants for constraints
    P = 40  # Total production capacity
    S = 35  # Total sales capacity
    
    # CRITICAL: Validate array lengths before indexing
    assert len(market_rates) == len(production_costs) == n_items, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_items)  # 1-based indexing
    
    # 4. PARAMETERS
    profit_margins = {i+1: market_rates[i] - production_costs[i] for i in range(n_items)}
    model.profit_margin = pyo.Param(model.I, initialize=profit_margins)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.profit_margin[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def production_capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= P
    model.production_capacity_constraint = pyo.Constraint(rule=production_capacity_rule)
    
    def sales_capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= S
    model.sales_capacity_constraint = pyo.Constraint(rule=sales_capacity_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    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}")
        
    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
furniture_optimization()