#!/usr/bin/env python3
"""
DOCplex implementation for pet care resource allocation optimization
"""

from docplex.mp.model import Model

def pet_care_optimization():
    """Optimize pet care resource allocation to minimize total cost"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="pet_care_optimization")
    
    # Data from the database
    pet_type_costs = {'dog': 50.0, 'cat': 30.0, 'bird': 20.0}
    pet_care_requirements = {'dog': (10.0, 100.0), 'cat': (5.0, 50.0), 'bird': (3.0, 30.0)}
    resource_allocation = {'pet1': 'dog', 'pet2': 'cat', 'pet3': 'bird'}
    
    # Business configuration parameter
    R = 200.0  # Maximum total resource allocation limit
    
    # CRITICAL: Validate array lengths to prevent IndexError
    n_pets = len(resource_allocation)
    assert n_pets > 0, "No pets found in resource_allocation"
    
    # 2. VARIABLES
    # Decision variables: amount of resources allocated to each pet
    x = {pet_id: mdl.continuous_var(name=f"x_{pet_id}", lb=0) for pet_id in resource_allocation}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of pet care
    objective = mdl.sum(pet_type_costs[resource_allocation[pet_id]] * x[pet_id] for pet_id in resource_allocation)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Minimum Care Requirement
    for pet_id in resource_allocation:
        pet_type = resource_allocation[pet_id]
        min_care = pet_care_requirements[pet_type][0]
        mdl.add_constraint(x[pet_id] >= min_care, ctname=f"min_care_{pet_id}")
    
    # Maximum Care Requirement
    for pet_id in resource_allocation:
        pet_type = resource_allocation[pet_id]
        max_care = pet_care_requirements[pet_type][1]
        mdl.add_constraint(x[pet_id] <= max_care, ctname=f"max_care_{pet_id}")
    
    # Total Resource Limit
    total_resources = mdl.sum(x[pet_id] for pet_id in resource_allocation)
    mdl.add_constraint(total_resources <= R, ctname="total_resource_limit")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for pet_id in resource_allocation:
            value = solution.get_value(x[pet_id])
            print(f"Resources allocated to {pet_id}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
if __name__ == "__main__":
    pet_care_optimization()