"""
MikoshiLang Extended Functions - Set 36
Manufacturing, production systems, and industrial engineering
"""
import sympy as sp
from sympy import symbols, sqrt, exp, log, pi

def get_rules():
    """Extended set 36: Manufacturing and industrial engineering (150 functions)"""
    x, t, n = symbols('x t n')
    
    return [
        # ===== PRODUCTION PLANNING (35 functions) =====
        ('ProductionRate[output_, time_]', lambda out, t: out/t),
        ('CycleTime[total_time_, units_]', lambda tt, units: tt/units),
        ('TaktTime[available_time_, demand_]', lambda at, d: at/d),
        ('LeadTime[processing_, waiting_, transport_]', lambda proc, wait, trans: proc + wait + trans),
        ('ThroughputTime[start_, end_]', lambda start, end: end - start),
        ('UtilizationRate[actual_, available_]', lambda actual, avail: actual/avail*100),
        ('EfficiencyRate[actual_, standard_]', lambda actual, std: actual/std*100),
        ('OverallEquipmentEffectiveness[availability_, performance_, quality_]', lambda A, P, Q: A*P*Q),
        ('AvailabilityFactor[uptime_, total_time_]', lambda up, tot: up/tot*100),
        ('PerformanceRate[actual_speed_, ideal_speed_]', lambda actual, ideal: actual/ideal*100),
        ('QualityRate[good_units_, total_units_]', lambda good, total: good/total*100),
        ('CapacityUtilization[actual_, capacity_]', lambda actual, cap: actual/cap*100),
        ('BottleneckIdentification[station_times_]', lambda times: max(times)),
        ('LineBalancing[task_times_, num_stations_]', lambda tt, n: sum(tt)/n),
        ('BalanceDelay[idle_time_, total_time_]', lambda idle, total: idle/total*100),
        ('SmoothingIndex[variation_, mean_]', lambda var, mean: var/mean),
        ('ProductionSmoothing[actual_, target_]', lambda actual, target: abs(actual - target)),
        ('MasterProductionSchedule[demand_, inventory_]', lambda d, inv: d - inv),
        ('MaterialRequirementsPlanning[gross_, scheduled_, on_hand_]', lambda gross, sched, oh: gross - sched - oh),
        ('SafetyStock[demand_variability_, lead_time_]', lambda dv, lt: dv*sqrt(lt)),
        ('ReorderPoint[demand_rate_, lead_time_, safety_stock_]', lambda dr, lt, ss: dr*lt + ss),
        ('EconomicOrderQuantity[demand_, ordering_cost_, holding_cost_]', lambda D, S, H: sqrt(2*D*S/H)),
        ('OrderingCost[orders_, cost_per_order_]', lambda orders, cpo: orders*cpo),
        ('HoldingCost[inventory_, holding_rate_]', lambda inv, hr: inv*hr),
        ('TotalInventoryCost[ordering_, holding_]', lambda ord, hold: ord + hold),
        ('InventoryTurnoverRatio[COGS_, avg_inventory_]', lambda cogs, inv: cogs/inv),
        ('DaysInventoryOutstanding[inventory_, daily_COGS_]', lambda inv, dcogs: inv/dcogs),
        ('StockoutCost[units_short_, cost_per_unit_]', lambda short, cpu: short*cpu),
        ('ServiceLevel[demand_met_, total_demand_]', lambda met, total: met/total*100),
        ('FillRate[lines_filled_, total_lines_]', lambda filled, total: filled/total*100),
        ('BackorderLevel[demand_, supply_]', lambda d, s: max(0, d - s)),
        ('LotSizing[setup_cost_, holding_cost_, demand_]', lambda setup, hold, d: sqrt(2*setup*d/hold)),
        ('CapacityRequirementPlanning[orders_, capacity_]', lambda orders, cap: orders/cap),
        ('LoadingFactor[load_, capacity_]', lambda load, cap: load/cap*100),
        ('SchedulingPriority[due_date_, processing_time_]', lambda dd, pt: dd - pt),
        
        # ===== QUALITY CONTROL (30 functions) =====
        ('DefectRate[defects_, total_]', lambda def_count, total: def_count/total*100),
        ('YieldRate[good_, total_]', lambda good, total: good/total*100),
        ('ScrapRate[scrap_, total_]', lambda scrap, total: scrap/total*100),
        ('ReworkRate[rework_, total_]', lambda rework, total: rework/total*100),
        ('FirstPassYield[good_first_, total_]', lambda good, total: good/total*100),
        ('RolledThroughputYield[FPY_stages_]', lambda fpys: sp.prod(fpys)),
        ('SigmaLevel[defects_per_million_]', lambda dpm: 6 - sp.log(dpm/1e6, 2.718)/sqrt(2)),
        ('ProcessCapability[tolerance_, process_variation_]', lambda tol, var: tol/(6*var)),
        ('CpIndex[USL_, LSL_, sigma_]', lambda USL, LSL, sigma: (USL - LSL)/(6*sigma)),
        ('CpkIndex[mean_, USL_, LSL_, sigma_]', lambda mean, USL, LSL, sigma: min((USL - mean)/(3*sigma), (mean - LSL)/(3*sigma))),
        ('PpmDefectRate[defects_, total_]', lambda def_count, total: def_count/total*1e6),
        ('ControlChartUCL[mean_, sigma_, n_]', lambda mean, sigma, n: mean + 3*sigma/sqrt(n)),
        ('ControlChartLCL[mean_, sigma_, n_]', lambda mean, sigma, n: mean - 3*sigma/sqrt(n)),
        ('ControlChartCenterLine[mean_]', lambda mean: mean),
        ('RChart Range[max_, min_]', lambda max_val, min_val: max_val - min_val),
        ('XBarChart[sample_mean_]', lambda xbar: xbar),
        ('PChart[defectives_, sample_size_]', lambda d, n: d/n),
        ('CChart[defects_]', lambda c: c),
        ('SampleSize[Z_, p_, E_]', lambda Z, p, E: (Z**2*p*(1 - p))/E**2),
        ('ConfidenceInterval[mean_, Z_, sigma_, n_]', lambda mean, Z, sigma, n: (mean - Z*sigma/sqrt(n), mean + Z*sigma/sqrt(n))),
        ('TypeIError[alpha_]', lambda alpha: alpha),
        ('TypeIIError[beta_]', lambda beta: beta),
        ('PowerOfTest[1_minus_beta_]', lambda beta: 1 - beta),
        ('AcceptanceSampling[n_, c_]', lambda n, c: (n, c)),
        ('AQL[acceptable_quality_level_]', lambda aql: aql),
        ('LTPD[lot_tolerance_percent_defective_]', lambda ltpd: ltpd),
        ('ProducerRisk[alpha_]', lambda alpha: alpha),
        ('ConsumerRisk[beta_]', lambda beta: beta),
        ('OperatingCharacteristicCurve[p_, n_, c_]', lambda p, n, c: sp.Symbol('Pa')),
        ('TaguchLossFunction[y_, target_, k_]', lambda y, T, k: k*(y - T)**2),
        
        # ===== LEAN MANUFACTURING (25 functions) =====
        ('ValueAddedTime[processing_time_]', lambda pt: pt),
        ('NonValueAddedTime[waiting_, transport_, inspection_]', lambda wait, trans, insp: wait + trans + insp),
        ('ValueAddedRatio[VA_time_, total_time_]', lambda va, total: va/total*100),
        ('ProcessCycleEfficiency[VA_time_, lead_time_]', lambda va, lt: va/lt*100),
        ('WorkInProgress[cycle_time_, throughput_]', lambda ct, tp: ct*tp),
        ('LittlesLaw[WIP_, throughput_]', lambda wip, tp: wip/tp),
        ('FlowTime[WIP_, arrival_rate_]', lambda wip, arr: wip/arr),
        ('WaitingTime[queue_length_, service_rate_]', lambda q, mu: q/mu),
        ('QueueLength[arrival_rate_, service_rate_]', lambda lam, mu: lam/(mu - lam)),
        ('ServerUtilization[arrival_rate_, service_rate_]', lambda lam, mu: lam/mu),
        ('SetupReduction[current_, improved_]', lambda curr, imp: (curr - imp)/curr*100),
        ('ChangeoverTime[setup_, adjust_, trial_]', lambda setup, adj, trial: setup + adj + trial),
        ('SMED[single_minute_exchange_]', lambda smed: smed < 10),
        ('PokayokeEffectiveness[defects_prevented_, total_defects_]', lambda prev, total: prev/total*100),
        ('KanbanCards[demand_, lead_time_, container_size_]', lambda d, lt, cs: d*lt/cs),
        ('PullSystemSize[daily_demand_, lead_time_days_]', lambda dd, ltd: dd*ltd),
        ('Supermarket Size[max_inventory_]', lambda max_inv: max_inv),
        ('KaizenEvents[improvements_]', lambda imp: imp),
        ('ValueStreamMapping[activities_]', lambda act: act),
        ('FlowEfficiency[processing_, total_]', lambda proc, total: proc/total*100),
        ('TransportationWaste[distance_, trips_]', lambda dist, trips: dist*trips),
        ('MotionWaste[unnecessary_movements_]', lambda moves: moves),
        ('OverproductionWaste[excess_]', lambda excess: excess),
        ('InventoryWaste[excess_stock_]', lambda stock: stock),
        ('DefectWaste[rework_cost_]', lambda cost: cost),
        
        # ===== MAINTENANCE (20 functions) =====
        ('MTBF[operating_time_, failures_]', lambda t, f: t/f),  # Alias
        ('MeanTimeBetweenFailures[operating_time_, failures_]', lambda t, f: t/f),
        ('MTTR[repair_time_, repairs_]', lambda t, r: t/r),  # Alias
        ('MeanTimeToRepair[repair_time_, repairs_]', lambda t, r: t/r),
        ('MTTF[total_time_, items_]', lambda t, n: t/n),  # Alias
        ('MeanTimeToFailure[total_time_, items_]', lambda t, n: t/n),
        ('Availability[MTBF_, MTTR_]', lambda mtbf, mttr: mtbf/(mtbf + mttr)*100),
        ('ReliabilityFunction[failure_rate_, t_]', lambda lam, t: exp(-lam*t)),
        ('FailureRate[failures_, operating_time_]', lambda f, t: f/t),
        ('HazardFunction[h_]', lambda h: h),
        ('WeibullDistribution[t_, beta_, eta_]', lambda t, beta, eta: (beta/eta)*(t/eta)**(beta - 1)*exp(-(t/eta)**beta)),
        ('BathtubCurve[infant_, random_, wearout_]', lambda inf, rand, wear: inf + rand + wear),
        ('PreventiveMaintenanceCost[PM_cost_, frequency_]', lambda cost, freq: cost*freq),
        ('CorrectiveMaintenanceCost[failure_cost_, failures_]', lambda cost, fail: cost*fail),
        ('TotalMaintenanceCost[PM_, CM_]', lambda pm, cm: pm + cm),
        ('OptimalPMInterval[Cf_, Cp_, MTBF_]', lambda Cf, Cp, mtbf: mtbf*sqrt(Cp/Cf)),
        ('SparePartsInventory[failure_rate_, lead_time_]', lambda fr, lt: fr*lt),
        ('ConditionMonitoring[vibration_, temperature_, oil_]', lambda vib, temp, oil: (vib, temp, oil)),
        ('PredictiveMaintenance[trend_]', lambda trend: trend),
        ('MaintenanceBacklog[pending_work_]', lambda pw: pw),
        ('PlanningSchedulingEfficiency[planned_, total_]', lambda plan, total: plan/total*100),
        ('WorkOrderCompletion[completed_, total_]', lambda comp, total: comp/total*100),
        ('MaintenanceCostAsPercentRevenue[maint_cost_, revenue_]', lambda mc, rev: mc/rev*100),
        
        # ===== ERGONOMICS & SAFETY (20 functions) =====
        ('IncidentRate[incidents_, hours_worked_]', lambda inc, hrs: inc/hrs*200000),
        ('LostTimeInjuryRate[LTI_, hours_]', lambda lti, hrs: lti/hrs*1000000),
        ('TotalRecordableRate[TRC_, hours_]', lambda trc, hrs: trc/hrs*200000),
        ('SeverityRate[days_lost_, hours_]', lambda days, hrs: days/hrs*200000),
        ('FrequencyRate[accidents_, hours_]', lambda acc, hrs: acc/hrs*1000000),
        ('LiftingLimit[weight_, vertical_, horizontal_, asymmetry_]', lambda w, v, h, a: 51*(25/h)*(1 - 0.0075*abs(v - 30))*(1 - 0.0032*a)),
        ('NISOHRevisedLiftingEquation[LC_, HM_, VM_, DM_, AM_, FM_, CM_]', lambda LC, HM, VM, DM, AM, FM, CM: LC*HM*VM*DM*AM*FM*CM),
        ('LiftingIndex[load_, RWL_]', lambda load, rwl: load/rwl),
        ('MetabolicRate[activity_level_]', lambda act: act),
        ('EnergyExpenditure[met_, time_]', lambda met, t: met*t),
        ('RestAllowance[work_load_, duration_]', lambda wl, dur: wl*dur/100),
        ('NoiseExposureLevel[dB_, hours_]', lambda db, hrs: db + 10*log(hrs/8, 10)),
        ('TimeWeightedAverage[concentrations_, times_]', lambda C, t: sum(Ci*ti for Ci, ti in zip(C, t))/sum(t)),
        ('PermissibleExposureLimit[PEL_]', lambda pel: pel),
        ('ThresholdLimitValue[TLV_]', lambda tlv: tlv),
        ('HeatStressIndex[temp_, humidity_]', lambda T, H: 0.5*T + 0.5*H),
        ('WetBulbGlobeTemperature[WBGT_]', lambda wbgt: wbgt),
        ('IlluminationLevel[lux_]', lambda lux: lux),
        ('GlareRating[luminance_]', lambda L: L),
        ('AnthromorphicData[percentile_]', lambda p: p),
        
        # ===== FACILITY LAYOUT (20 functions) =====
        ('MaterialHandlingCost[distance_, trips_, cost_per_trip_]', lambda d, trips, cpt: d*trips*cpt),
        ('DistanceMatrix[locations_]', lambda locs: sp.Symbol('D')),
        ('FlowMatrix[from_to_]', lambda ft: sp.Symbol('F')),
        ('TotalMovementCost[flow_, distance_]', lambda F, D: sum(sum(Fij*Dij for Fij, Dij in zip(Fi, Di)) for Fi, Di in zip(F, D))),
        ('ClosenessRating[rating_]', lambda r: r),
        ('ActivityRelationshipChart[departments_]', lambda depts: sp.Symbol('ARC')),
        ('SpaceRequirement[machines_, area_per_machine_]', lambda m, a: m*a),
        ('FromToChart[trips_]', lambda trips: sp.Symbol('FT')),
        ('SystematicLayoutPlanning[SLP_]', lambda slp: slp),
        ('BlockLayout[blocks_]', lambda b: b),
        ('DetailedLayout[equipment_positions_]', lambda eq: eq),
        ('AisleWidth[traffic_, clearance_]', lambda traf, clear: traf + clear),
        ('ColumnSpacing[span_]', lambda span: span),
        ('CeilingHeight[equipment_, clearance_]', lambda eq, clear: eq + clear),
        ('LoadingDockCapacity[trucks_per_hour_]', lambda tph: tph),
        ('StorageCapacity[volume_]', lambda V: V),
        ('WarehouseUtilization[used_, total_]', lambda used, total: used/total*100),
        ('PickingEfficiency[orders_, time_]', lambda orders, t: orders/t),
        ('CrossDocking[incoming_, outgoing_]', lambda inc, out: inc == out),
        ('SlottingOptimization[ABC_classification_]', lambda abc: abc),
    ]

def register():
    """Register all extended36 rules"""
    from .extended_helper import convert_rules
    return convert_rules(get_rules())
