#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Medicine Selection Optimization Problem
"""

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

def medicine_selection_optimization():
    """Optimize medicine selection for clinical trial"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    medicine_ids = [1, 2, 3]
    effectiveness_scores = [0.85, 0.75, 0.9]
    adverse_interaction_scores = [0.15, 0.25, 0.1]
    FDA_approved = [True, False, True]
    
    # CRITICAL: Validate array lengths before indexing
    assert len(medicine_ids) == len(effectiveness_scores) == len(adverse_interaction_scores) == len(FDA_approved), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=medicine_ids)  # Medicine IDs
    
    # 4. PARAMETERS
    model.effectiveness = pyo.Param(model.I, initialize={i: s for i, s in zip(medicine_ids, effectiveness_scores)})
    model.adverse_interaction = pyo.Param(model.I, initialize={i: s for i, s in zip(medicine_ids, adverse_interaction_scores)})
    model.FDA_approved = pyo.Param(model.I, initialize={i: a for i, a in zip(medicine_ids, FDA_approved)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)  # Selection decision variables
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.effectiveness[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Adverse Interaction Limit
    def adverse_interaction_rule(model):
        return sum(model.adverse_interaction[i] * model.x[i] for i in model.I) <= 0.5
    model.adverse_interaction_constraint = pyo.Constraint(rule=adverse_interaction_rule)
    
    # Medicine Count Limit
    def medicine_count_rule(model):
        return sum(model.x[i] for i in model.I) <= 3
    model.medicine_count_constraint = pyo.Constraint(rule=medicine_count_rule)
    
    # FDA Approval Requirement
    def FDA_approval_rule(model, i):
        if not model.FDA_approved[i]:
            return model.x[i] == 0
        return pyo.Constraint.Skip
    model.FDA_approval_constraint = pyo.Constraint(model.I, rule=FDA_approval_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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected Medicines:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected medicines
                print(f"Medicine {i} is selected")
        
    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

if __name__ == "__main__":
    medicine_selection_optimization()