#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Office Space Allocation Optimization
"""

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

def optimize_office_allocation():
    """Optimize the allocation of office spaces across multiple buildings to minimize total leasing cost."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define sets for companies and buildings
    companies = [1, 2, 3]
    buildings = [1, 2, 3]
    
    # Cost per square foot for each building
    cost_per_sqft = {
        1: 55.0,
        2: 65.0,
        3: 45.0
    }
    
    # Minimum space required by each company
    required_space = {
        1: 1200,
        2: 1800,
        3: 900
    }
    
    # Total available space in each building
    available_space = {
        1: 6000,
        2: 7000,
        3: 5000
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(cost_per_sqft) == len(buildings), "Cost per sqft data length mismatch"
    assert len(required_space) == len(companies), "Required space data length mismatch"
    assert len(available_space) == len(buildings), "Available space data length mismatch"
    
    # 3. SETS
    model.companies = pyo.Set(initialize=companies)
    model.buildings = pyo.Set(initialize=buildings)
    
    # 4. PARAMETERS
    model.cost_per_sqft = pyo.Param(model.buildings, initialize=cost_per_sqft)
    model.required_space = pyo.Param(model.companies, initialize=required_space)
    model.available_space = pyo.Param(model.buildings, initialize=available_space)
    
    # 5. VARIABLES
    model.space_allocated = pyo.Var(model.companies, model.buildings, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost_per_sqft[j] * model.space_allocated[i, j] for i in model.companies for j in model.buildings)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Minimum Space Requirement
    def min_space_rule(model, i):
        return sum(model.space_allocated[i, j] for j in model.buildings) >= model.required_space[i]
    model.min_space_constraint = pyo.Constraint(model.companies, rule=min_space_rule)
    
    # Building Capacity
    def building_capacity_rule(model, j):
        return sum(model.space_allocated[i, j] for i in model.companies) <= model.available_space[j]
    model.building_capacity_constraint = pyo.Constraint(model.buildings, rule=building_capacity_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("\nSpace Allocated:")
        for i in model.companies:
            for j in model.buildings:
                allocated = pyo.value(model.space_allocated[i, j])
                if allocated > 1e-6:  # Only print non-zero values
                    print(f"Company {i} in Building {j}: {allocated:.2f} sqft")
        
    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

# Execute the optimization
if __name__ == "__main__":
    optimize_office_allocation()