# Complete PYOMO implementation

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

def wine_optimization():
    """Optimize wine production to maximize revenue"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    prices = [12.0, 18.0, 22.0]
    market_demands = [500, 800, 300]
    total_capacity = 500
    
    # CRITICAL: Validate array lengths before indexing
    assert len(prices) == len(market_demands), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, len(prices))  # 1-based indexing
    
    # 4. PARAMETERS
    model.price = pyo.Param(model.I, initialize={i+1: prices[i] for i in range(len(prices))})
    model.demand = pyo.Param(model.I, initialize={i+1: market_demands[i] for i in range(len(market_demands))})
    
    # 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 capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= total_capacity
    model.capacity_constraint = pyo.Constraint(rule=capacity_rule)
    
    # Market Demand Constraints
    def demand_rule(model, i):
        return model.x[i] <= model.demand[i]
    model.demand_constraint = pyo.Constraint(model.I, rule=demand_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):.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:.2f}")
        
    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
wine_optimization()