# Complete PYOMO implementation

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

def pet_care_optimization():
    """Optimize pet care resource allocation to minimize total cost."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Pet types and their costs
    pet_type_costs = {'dog': 50.0, 'cat': 30.0, 'bird': 20.0}
    
    # Pet care requirements (min and max care per pet type)
    pet_care_requirements = {
        'dog': {'min_care': 10.0, 'max_care': 100.0},
        'cat': {'min_care': 5.0, 'max_care': 50.0},
        'bird': {'min_care': 3.0, 'max_care': 30.0}
    }
    
    # Resource allocation data (pet_id and initial amount)
    resource_allocation = {
        'pet1': {'pet_type': 'dog', 'amount': 50.0},
        'pet2': {'pet_type': 'cat', 'amount': 30.0},
        'pet3': {'pet_type': 'bird', 'amount': 20.0}
    }
    
    # Maximum total resource allocation limit
    R = 200.0
    
    # 3. SETS (Pyomo way to define indices)
    model.P = pyo.Set(initialize=resource_allocation.keys())  # Set of pets
    
    # 4. PARAMETERS (data containers)
    model.cost = pyo.Param(model.P, initialize={p: pet_type_costs[resource_allocation[p]['pet_type']] for p in model.P})
    model.min_care = pyo.Param(model.P, initialize={p: pet_care_requirements[resource_allocation[p]['pet_type']]['min_care'] for p in model.P})
    model.max_care = pyo.Param(model.P, initialize={p: pet_care_requirements[resource_allocation[p]['pet_type']]['max_care'] for p in model.P})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.P, within=pyo.NonNegativeReals)  # Resources allocated to each pet
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[p] * model.x[p] for p in model.P)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Minimum care requirement
    def min_care_rule(model, p):
        return model.x[p] >= model.min_care[p]
    model.min_care_constraint = pyo.Constraint(model.P, rule=min_care_rule)
    
    # Maximum care requirement
    def max_care_rule(model, p):
        return model.x[p] <= model.max_care[p]
    model.max_care_constraint = pyo.Constraint(model.P, rule=max_care_rule)
    
    # Total resource limit
    def total_resource_rule(model):
        return sum(model.x[p] for p in model.P) <= R
    model.total_resource_constraint = pyo.Constraint(rule=total_resource_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("\nResource allocation:")
        for p in model.P:
            x_val = pyo.value(model.x[p])
            print(f"Pet {p}: {x_val:.3f} resources")
        
    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__":
    pet_care_optimization()