# Complete PYOMO implementation

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

def network_optimization():
    """Optimization for maximizing influence in a social network under budget constraints"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the problem statement
    influence_values = [1.5, 0.9, 1.2]
    targeting_costs = [300.0, 150.0, 250.0]
    budget = 500.0
    
    # Validate array lengths
    n_people = len(influence_values)
    assert len(targeting_costs) == n_people, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_people)  # 1-based indexing
    
    # 4. PARAMETERS
    model.influence = pyo.Param(model.I, initialize={i+1: influence_values[i] for i in range(n_people)})
    model.cost = pyo.Param(model.I, initialize={i+1: targeting_costs[i] for i in range(n_people)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.influence[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def budget_constraint_rule(model):
        return sum(model.cost[i] * model.x[i] for i in model.I) <= budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_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("\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}] = {int(x_val)}")
        
    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
network_optimization()