# Complete PYOMO implementation

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

def wine_optimization():
    """Pyomo implementation for the wine production optimization problem."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Profit per case for each wine type
    profits = [10.5, 15.0, 20.0]
    # Grape usage per case for each wine type
    grape_usages = [2.5, 3.0, 4.0]
    # Production cost per case for each wine type
    production_costs = [5.0, 6.0, 7.0]
    # Market demand for each wine type
    market_demands = [100, 150, 200]
    # Total budget available for production
    total_budget = 100000
    # Total grapes available (assumed value, not provided in the data)
    total_grapes_available = 1000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(profits) == len(grape_usages) == len(production_costs) == len(market_demands), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, len(profits))  # 1-based indexing for wine types
    
    # 4. PARAMETERS (data containers)
    model.profit = pyo.Param(model.I, initialize={i+1: profits[i] for i in range(len(profits))})
    model.grape_usage = pyo.Param(model.I, initialize={i+1: grape_usages[i] for i in range(len(grape_usages))})
    model.production_cost = pyo.Param(model.I, initialize={i+1: production_costs[i] for i in range(len(production_costs))})
    model.market_demand = pyo.Param(model.I, initialize={i+1: market_demands[i] for i in range(len(market_demands))})
    model.total_budget = pyo.Param(initialize=total_budget)
    model.total_grapes_available = pyo.Param(initialize=total_grapes_available)
    
    # 5. VARIABLES
    # Number of cases to produce for each wine type (must be integer)
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.profit[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Grape availability constraint
    def grape_availability_rule(model):
        return sum(model.grape_usage[i] * model.x[i] for i in model.I) <= model.total_grapes_available
    model.grape_availability_constraint = pyo.Constraint(rule=grape_availability_rule)
    
    # Production budget constraint
    def budget_rule(model):
        return sum(model.production_cost[i] * model.x[i] for i in model.I) <= model.total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Market demand constraint
    def market_demand_rule(model, i):
        return model.x[i] <= model.market_demand[i]
    model.market_demand_constraint = pyo.Constraint(model.I, rule=market_demand_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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:.0f}")
        
    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
if __name__ == "__main__":
    wine_optimization()