import * as plugins from '../../plugins.js';
import type { IIntegrationEntity, IServiceCallRequest, TEntityPlatform } from '../../core/types.js';
import type { IHomekitAccessory, IHomekitCharacteristic, IHomekitCharacteristicReference, IHomekitCharacteristicWrite, IHomekitControllerCommand, IHomekitControllerConfig, IHomekitControllerSnapshot, IHomekitService } from './homekit_controller.types.js';

type TKnownService =
  | 'accessory_information'
  | 'air_purifier'
  | 'air_quality_sensor'
  | 'battery_service'
  | 'camera_rtp_stream_management'
  | 'carbon_dioxide_sensor'
  | 'carbon_monoxide_sensor'
  | 'contact_sensor'
  | 'fan'
  | 'fan_v2'
  | 'garage_door_opener'
  | 'heater_cooler'
  | 'humidity_sensor'
  | 'leak_sensor'
  | 'light_sensor'
  | 'lightbulb'
  | 'lock_mechanism'
  | 'motion_sensor'
  | 'occupancy_sensor'
  | 'outlet'
  | 'smoke_sensor'
  | 'switch'
  | 'temperature_sensor'
  | 'thermostat'
  | 'window'
  | 'window_covering'
  | 'unknown';

type TKnownCharacteristic =
  | 'active'
  | 'air_quality'
  | 'battery_level'
  | 'brightness'
  | 'carbon_dioxide_detected'
  | 'carbon_dioxide_level'
  | 'carbon_monoxide_detected'
  | 'charging_state'
  | 'color_temperature'
  | 'contact_state'
  | 'current_door_state'
  | 'current_heater_cooler_state'
  | 'current_heating_cooling_state'
  | 'current_humidity'
  | 'current_light_level'
  | 'current_position'
  | 'current_temperature'
  | 'firmware_revision'
  | 'hardware_revision'
  | 'heating_cooling_target'
  | 'heating_threshold_temperature'
  | 'cooling_threshold_temperature'
  | 'hold_position'
  | 'hue'
  | 'identify'
  | 'leak_detected'
  | 'lock_current_state'
  | 'lock_target_state'
  | 'manufacturer'
  | 'model'
  | 'motion_detected'
  | 'name'
  | 'obstruction_detected'
  | 'occupancy_detected'
  | 'on'
  | 'outlet_in_use'
  | 'position_state'
  | 'rotation_direction'
  | 'rotation_speed'
  | 'saturation'
  | 'serial_number'
  | 'smoke_detected'
  | 'status_low_battery'
  | 'swing_mode'
  | 'target_door_state'
  | 'target_heater_cooler_state'
  | 'target_humidity'
  | 'target_position'
  | 'target_temperature'
  | 'unknown';

interface IAccessoryInfo {
  name: string;
  manufacturer?: string;
  model?: string;
  serialNumber?: string;
  firmwareRevision?: string;
  hardwareRevision?: string;
}

interface IMappedService {
  accessory: IHomekitAccessory;
  service: IHomekitService;
  serviceType: TKnownService;
  platform: TEntityPlatform;
  name: string;
  state: unknown;
  attributes: Record<string, unknown>;
  featureId: string;
  capability: plugins.shxInterfaces.data.TDeviceCapability;
  writable: boolean;
}

const serviceTypeByToken: Record<string, TKnownService> = {
  '0000003e': 'accessory_information',
  accessory_information: 'accessory_information',
  public_hap_service_accessory_information: 'accessory_information',
  '000000bb': 'air_purifier',
  air_purifier: 'air_purifier',
  public_hap_service_airpurifier: 'air_purifier',
  '0000008d': 'air_quality_sensor',
  air_quality_sensor: 'air_quality_sensor',
  public_hap_service_air_quality_sensor: 'air_quality_sensor',
  '00000096': 'battery_service',
  battery: 'battery_service',
  battery_service: 'battery_service',
  public_hap_service_battery_service: 'battery_service',
  '00000110': 'camera_rtp_stream_management',
  camera_rtp_stream_management: 'camera_rtp_stream_management',
  public_hap_service_camera_rtp_stream_management: 'camera_rtp_stream_management',
  '00000097': 'carbon_dioxide_sensor',
  carbon_dioxide_sensor: 'carbon_dioxide_sensor',
  public_hap_service_carbon_dioxide_sensor: 'carbon_dioxide_sensor',
  '0000007f': 'carbon_monoxide_sensor',
  carbon_monoxide_sensor: 'carbon_monoxide_sensor',
  public_hap_service_carbon_monoxide_sensor: 'carbon_monoxide_sensor',
  '00000080': 'contact_sensor',
  contact_sensor: 'contact_sensor',
  public_hap_service_contact_sensor: 'contact_sensor',
  '00000040': 'fan',
  fan: 'fan',
  public_hap_service_fan: 'fan',
  '000000b7': 'fan_v2',
  fan_v2: 'fan_v2',
  fanv2: 'fan_v2',
  public_hap_service_fanv2: 'fan_v2',
  '00000041': 'garage_door_opener',
  garage_door_opener: 'garage_door_opener',
  public_hap_service_garage_door_opener: 'garage_door_opener',
  '000000bc': 'heater_cooler',
  heater_cooler: 'heater_cooler',
  public_hap_service_heater_cooler: 'heater_cooler',
  '00000082': 'humidity_sensor',
  humidity_sensor: 'humidity_sensor',
  public_hap_service_humidity_sensor: 'humidity_sensor',
  '00000083': 'leak_sensor',
  leak_sensor: 'leak_sensor',
  public_hap_service_leak_sensor: 'leak_sensor',
  '00000084': 'light_sensor',
  light_sensor: 'light_sensor',
  public_hap_service_light_sensor: 'light_sensor',
  '00000043': 'lightbulb',
  lightbulb: 'lightbulb',
  light_bulb: 'lightbulb',
  public_hap_service_lightbulb: 'lightbulb',
  '00000045': 'lock_mechanism',
  lock_mechanism: 'lock_mechanism',
  public_hap_service_lock_mechanism: 'lock_mechanism',
  '00000085': 'motion_sensor',
  motion_sensor: 'motion_sensor',
  public_hap_service_motion_sensor: 'motion_sensor',
  '00000086': 'occupancy_sensor',
  occupancy_sensor: 'occupancy_sensor',
  public_hap_service_occupancy_sensor: 'occupancy_sensor',
  '00000047': 'outlet',
  outlet: 'outlet',
  public_hap_service_outlet: 'outlet',
  '00000087': 'smoke_sensor',
  smoke_sensor: 'smoke_sensor',
  public_hap_service_smoke_sensor: 'smoke_sensor',
  '00000049': 'switch',
  switch: 'switch',
  public_hap_service_switch: 'switch',
  '0000008a': 'temperature_sensor',
  temperature_sensor: 'temperature_sensor',
  public_hap_service_temperature_sensor: 'temperature_sensor',
  '0000004a': 'thermostat',
  thermostat: 'thermostat',
  public_hap_service_thermostat: 'thermostat',
  '0000008b': 'window',
  window: 'window',
  public_hap_service_window: 'window',
  '0000008c': 'window_covering',
  window_covering: 'window_covering',
  public_hap_service_window_covering: 'window_covering',
};

const characteristicTypeByToken: Record<string, TKnownCharacteristic> = {
  '000000b0': 'active',
  active: 'active',
  '00000095': 'air_quality',
  air_quality: 'air_quality',
  '00000068': 'battery_level',
  battery_level: 'battery_level',
  '00000008': 'brightness',
  brightness: 'brightness',
  '00000092': 'carbon_dioxide_detected',
  carbon_dioxide_detected: 'carbon_dioxide_detected',
  '00000093': 'carbon_dioxide_level',
  carbon_dioxide_level: 'carbon_dioxide_level',
  '00000069': 'carbon_monoxide_detected',
  carbon_monoxide_detected: 'carbon_monoxide_detected',
  '0000008f': 'charging_state',
  charging_state: 'charging_state',
  '000000ce': 'color_temperature',
  color_temperature: 'color_temperature',
  '0000006a': 'contact_state',
  contact_sensor_state: 'contact_state',
  contact_state: 'contact_state',
  '0000000e': 'current_door_state',
  current_door_state: 'current_door_state',
  '000000b1': 'current_heater_cooler_state',
  current_heater_cooler_state: 'current_heater_cooler_state',
  '0000000f': 'current_heating_cooling_state',
  current_heating_cooling_state: 'current_heating_cooling_state',
  '00000010': 'current_humidity',
  current_relative_humidity: 'current_humidity',
  '0000006b': 'current_light_level',
  current_ambient_light_level: 'current_light_level',
  '0000006d': 'current_position',
  current_position: 'current_position',
  '00000011': 'current_temperature',
  current_temperature: 'current_temperature',
  '00000052': 'firmware_revision',
  firmware_revision: 'firmware_revision',
  '00000053': 'hardware_revision',
  hardware_revision: 'hardware_revision',
  '00000033': 'heating_cooling_target',
  target_heating_cooling_state: 'heating_cooling_target',
  heating_cooling_target: 'heating_cooling_target',
  '00000012': 'heating_threshold_temperature',
  heating_threshold_temperature: 'heating_threshold_temperature',
  '0000000d': 'cooling_threshold_temperature',
  cooling_threshold_temperature: 'cooling_threshold_temperature',
  '0000006f': 'hold_position',
  hold_position: 'hold_position',
  '00000013': 'hue',
  hue: 'hue',
  '00000014': 'identify',
  identify: 'identify',
  '00000070': 'leak_detected',
  leak_detected: 'leak_detected',
  '0000001d': 'lock_current_state',
  lock_current_state: 'lock_current_state',
  '0000001e': 'lock_target_state',
  lock_target_state: 'lock_target_state',
  '00000020': 'manufacturer',
  manufacturer: 'manufacturer',
  '00000021': 'model',
  model: 'model',
  '00000022': 'motion_detected',
  motion_detected: 'motion_detected',
  '00000023': 'name',
  name: 'name',
  '00000024': 'obstruction_detected',
  obstruction_detected: 'obstruction_detected',
  '00000071': 'occupancy_detected',
  occupancy_detected: 'occupancy_detected',
  '00000025': 'on',
  on: 'on',
  '00000026': 'outlet_in_use',
  outlet_in_use: 'outlet_in_use',
  '00000072': 'position_state',
  position_state: 'position_state',
  '00000028': 'rotation_direction',
  rotation_direction: 'rotation_direction',
  '00000029': 'rotation_speed',
  rotation_speed: 'rotation_speed',
  '0000002f': 'saturation',
  saturation: 'saturation',
  '00000030': 'serial_number',
  serial_number: 'serial_number',
  '00000076': 'smoke_detected',
  smoke_detected: 'smoke_detected',
  '00000079': 'status_low_battery',
  status_low_battery: 'status_low_battery',
  '000000b6': 'swing_mode',
  swing_mode: 'swing_mode',
  '00000032': 'target_door_state',
  target_door_state: 'target_door_state',
  '000000b2': 'target_heater_cooler_state',
  target_heater_cooler_state: 'target_heater_cooler_state',
  '00000034': 'target_humidity',
  target_relative_humidity: 'target_humidity',
  '0000007c': 'target_position',
  target_position: 'target_position',
  '00000035': 'target_temperature',
  target_temperature: 'target_temperature',
};

const writableCharacteristics = new Set<TKnownCharacteristic>([
  'active',
  'brightness',
  'color_temperature',
  'cooling_threshold_temperature',
  'heating_cooling_target',
  'heating_threshold_temperature',
  'hold_position',
  'hue',
  'identify',
  'lock_target_state',
  'on',
  'rotation_direction',
  'rotation_speed',
  'saturation',
  'swing_mode',
  'target_door_state',
  'target_heater_cooler_state',
  'target_humidity',
  'target_position',
  'target_temperature',
]);

export class HomekitControllerMapper {
  public static toSnapshot(configArg: IHomekitControllerConfig, connectedArg = false, eventsArg: IHomekitControllerSnapshot['events'] = []): IHomekitControllerSnapshot {
    const snapshot = configArg.snapshot;
    return {
      id: snapshot?.id || configArg.id || configArg.pairingData?.AccessoryPairingID,
      name: snapshot?.name || configArg.name,
      host: snapshot?.host || configArg.host || configArg.pairingData?.AccessoryIP,
      port: snapshot?.port || configArg.port || configArg.pairingData?.AccessoryPort,
      paired: snapshot?.paired ?? configArg.paired ?? Boolean(configArg.pairingData),
      connected: connectedArg || snapshot?.connected || configArg.connected || false,
      transport: snapshot?.transport || configArg.transport || (configArg.host || configArg.pairingData?.AccessoryIP ? 'ip' : 'snapshot'),
      configNumber: snapshot?.configNumber || configArg.configNumber,
      stateNumber: snapshot?.stateNumber || configArg.stateNumber,
      pairingData: snapshot?.pairingData || configArg.pairingData,
      discovery: snapshot?.discovery || configArg.discovery,
      accessories: snapshot?.accessories || configArg.accessories || [],
      events: eventsArg.length ? eventsArg : snapshot?.events || [],
    };
  }

  public static toDevices(snapshotArg: IHomekitControllerSnapshot): plugins.shxInterfaces.data.IDeviceDefinition[] {
    const updatedAt = new Date().toISOString();
    const mapped = this.mappedServices(snapshotArg);
    return snapshotArg.accessories.map((accessoryArg) => {
      const info = this.accessoryInfo(accessoryArg);
      const services = mapped.filter((mappedArg) => mappedArg.accessory === accessoryArg);
      const features = services.map((mappedArg): plugins.shxInterfaces.data.IDeviceFeature => ({
        id: mappedArg.featureId,
        capability: mappedArg.capability,
        name: mappedArg.name,
        readable: true,
        writable: mappedArg.writable,
        unit: typeof mappedArg.attributes.unit === 'string' ? mappedArg.attributes.unit : undefined,
      }));
      const state = services.map((mappedArg): plugins.shxInterfaces.data.IDeviceState => ({
        featureId: mappedArg.featureId,
        value: this.deviceStateValue(mappedArg.state),
        updatedAt,
      }));

      if (!features.length) {
        features.push({ id: 'accessory', capability: 'sensor', name: 'Accessory', readable: true, writable: false });
        state.push({ featureId: 'accessory', value: 'configured', updatedAt });
      }

      return {
        id: this.deviceId(snapshotArg, accessoryArg),
        integrationDomain: 'homekit_controller',
        name: info.name,
        protocol: 'homekit',
        manufacturer: info.manufacturer || snapshotArg.discovery?.manufacturer,
        model: info.model || snapshotArg.discovery?.model,
        online: snapshotArg.connected || Boolean(snapshotArg.accessories.length),
        features,
        state,
        metadata: {
          aid: accessoryArg.aid,
          pairingId: snapshotArg.id || snapshotArg.pairingData?.AccessoryPairingID,
          serialNumber: info.serialNumber,
          firmwareRevision: info.firmwareRevision,
          hardwareRevision: info.hardwareRevision,
          configNumber: snapshotArg.configNumber,
          stateNumber: snapshotArg.stateNumber,
          transport: snapshotArg.transport,
        },
      };
    });
  }

  public static toEntities(snapshotArg: IHomekitControllerSnapshot): IIntegrationEntity[] {
    return this.mappedServices(snapshotArg).map((mappedArg) => ({
      id: `${String(mappedArg.platform)}.${this.slug(mappedArg.name)}`,
      uniqueId: `homekit_controller_${this.slug(`${snapshotArg.id || snapshotArg.pairingData?.AccessoryPairingID || 'snapshot'}_${mappedArg.accessory.aid}_${mappedArg.service.iid}`)}`,
      integrationDomain: 'homekit_controller',
      deviceId: this.deviceId(snapshotArg, mappedArg.accessory),
      platform: mappedArg.platform,
      name: mappedArg.name,
      state: mappedArg.state,
      attributes: mappedArg.attributes,
      available: snapshotArg.connected || this.serviceHasValues(mappedArg.service),
    }));
  }

  public static commandForService(snapshotArg: IHomekitControllerSnapshot, requestArg: IServiceCallRequest): IHomekitControllerCommand | undefined {
    if (requestArg.domain === 'homekit_controller') {
      return this.commandFromHomekitService(snapshotArg, requestArg);
    }

    if (requestArg.domain === 'camera' && ['snapshot', 'camera_image', 'camera_snapshot'].includes(requestArg.service)) {
      const target = this.findTargetService(snapshotArg, requestArg);
      return target && this.serviceType(target.service.type) === 'camera_rtp_stream_management'
        ? { command: 'camera_snapshot', aid: target.accessory.aid, width: this.numberValue(requestArg.data?.width), height: this.numberValue(requestArg.data?.height) }
        : undefined;
    }

    const target = this.findTargetService(snapshotArg, requestArg);
    if (!target) {
      return undefined;
    }

    const serviceType = this.serviceType(target.service.type);
    const writes = this.writesForEntityService(target.accessory, target.service, serviceType, requestArg);
    return writes.length ? { command: 'write_characteristics', writes } : undefined;
  }

  public static serviceType(valueArg?: string): TKnownService {
    return serviceTypeByToken[this.typeToken(valueArg)] || 'unknown';
  }

  public static characteristicType(valueArg?: string): TKnownCharacteristic {
    return characteristicTypeByToken[this.typeToken(valueArg)] || 'unknown';
  }

  private static mappedServices(snapshotArg: IHomekitControllerSnapshot): IMappedService[] {
    const mapped: IMappedService[] = [];
    for (const accessory of snapshotArg.accessories) {
      for (const service of this.accessoryServices(accessory)) {
        const serviceType = this.serviceType(service.type);
        if (serviceType === 'accessory_information' || serviceType === 'unknown') {
          continue;
        }
        const platform = this.platformForService(serviceType);
        if (!platform) {
          continue;
        }
        const state = this.entityState(service, serviceType);
        mapped.push({
          accessory,
          service,
          serviceType,
          platform,
          name: this.entityName(accessory, service, serviceType),
          state,
          attributes: this.entityAttributes(accessory, service, serviceType),
          featureId: `service_${service.iid}_${serviceType}`,
          capability: this.capabilityForPlatform(platform),
          writable: this.serviceWritable(service, serviceType),
        });
      }
    }
    return mapped;
  }

  private static commandFromHomekitService(snapshotArg: IHomekitControllerSnapshot, requestArg: IServiceCallRequest): IHomekitControllerCommand | undefined {
    if (requestArg.service === 'snapshot') {
      return { command: 'snapshot' };
    }
    if (requestArg.service === 'pair' || requestArg.service === 'pair_setup') {
      return { command: 'pair_setup' };
    }
    if (requestArg.service === 'pair_verify') {
      return { command: 'pair_verify' };
    }
    if (requestArg.service === 'subscribe_events') {
      return { command: 'subscribe_events' };
    }
    if (requestArg.service === 'read_characteristics') {
      const reads = this.referencesFromData(requestArg.data);
      return reads.length ? { command: 'read_characteristics', reads } : undefined;
    }
    if (requestArg.service === 'write_characteristics') {
      const writes = this.writesFromData(requestArg.data);
      return writes.length ? { command: 'write_characteristics', writes } : undefined;
    }
    if (requestArg.service === 'identify') {
      const accessory = this.findTargetAccessory(snapshotArg, requestArg);
      const info = accessory ? this.accessoryServices(accessory).find((serviceArg) => this.serviceType(serviceArg.type) === 'accessory_information') : undefined;
      const char = info ? this.char(info, 'identify') : undefined;
      return accessory && info && char ? { command: 'identify', writes: [{ aid: accessory.aid, iid: char.iid, type: char.type, serviceIid: info.iid, serviceType: info.type, value: true }] } : undefined;
    }
    if (requestArg.service === 'camera_snapshot') {
      const accessory = this.findTargetAccessory(snapshotArg, requestArg);
      return { command: 'camera_snapshot', aid: accessory?.aid || this.numberValue(requestArg.data?.aid), width: this.numberValue(requestArg.data?.width), height: this.numberValue(requestArg.data?.height) };
    }
    return undefined;
  }

  private static writesForEntityService(accessoryArg: IHomekitAccessory, serviceArg: IHomekitService, serviceTypeArg: TKnownService, requestArg: IServiceCallRequest): IHomekitCharacteristicWrite[] {
    const direct = this.writesFromData(requestArg.data);
    if (requestArg.service === 'set_value' && direct.length) {
      return direct;
    }

    if (requestArg.service === 'turn_on' || requestArg.service === 'turn_off') {
      const on = requestArg.service === 'turn_on';
      const writes: IHomekitCharacteristicWrite[] = [];
      const onChar = this.primaryOnCharacteristic(serviceArg, serviceTypeArg);
      if (onChar) {
        writes.push(this.write(accessoryArg, serviceArg, onChar, this.characteristicType(onChar.type) === 'active' ? (on ? 1 : 0) : on));
      }
      const brightness = this.brightnessValue(requestArg.data);
      const brightnessChar = this.char(serviceArg, 'brightness');
      if (on && brightness !== undefined && brightnessChar) {
        writes.push(this.write(accessoryArg, serviceArg, brightnessChar, brightness));
      }
      const percentage = this.numberValue(requestArg.data?.percentage);
      const speedChar = this.char(serviceArg, 'rotation_speed');
      if (on && percentage !== undefined && speedChar && (serviceTypeArg === 'fan' || serviceTypeArg === 'fan_v2' || serviceTypeArg === 'air_purifier')) {
        writes.push(this.write(accessoryArg, serviceArg, speedChar, this.clampPercent(percentage)));
      }
      return writes;
    }

    if (requestArg.service === 'set_percentage') {
      const percentage = this.numberValue(requestArg.data?.percentage);
      const speedChar = this.char(serviceArg, 'rotation_speed');
      if (percentage === undefined || !speedChar) {
        return [];
      }
      const writes: IHomekitCharacteristicWrite[] = [this.write(accessoryArg, serviceArg, speedChar, this.clampPercent(percentage))];
      const onChar = this.primaryOnCharacteristic(serviceArg, serviceTypeArg);
      if (onChar) {
        writes.push(this.write(accessoryArg, serviceArg, onChar, this.characteristicType(onChar.type) === 'active' ? (percentage > 0 ? 1 : 0) : percentage > 0));
      }
      return writes;
    }

    if (requestArg.service === 'set_position' || requestArg.service === 'set_cover_position') {
      const position = this.numberValue(requestArg.data?.position);
      const target = this.char(serviceArg, 'target_position');
      return position !== undefined && target ? [this.write(accessoryArg, serviceArg, target, this.clampPercent(position))] : [];
    }

    if (requestArg.service === 'stop_cover') {
      const hold = this.char(serviceArg, 'hold_position');
      return hold ? [this.write(accessoryArg, serviceArg, hold, true)] : [];
    }

    if (requestArg.service === 'open_cover' || requestArg.service === 'close_cover') {
      const open = requestArg.service === 'open_cover';
      if (serviceTypeArg === 'garage_door_opener') {
        const target = this.char(serviceArg, 'target_door_state');
        return target ? [this.write(accessoryArg, serviceArg, target, open ? 0 : 1)] : [];
      }
      const target = this.char(serviceArg, 'target_position');
      return target ? [this.write(accessoryArg, serviceArg, target, open ? 100 : 0)] : [];
    }

    if (requestArg.service === 'lock' || requestArg.service === 'unlock') {
      const target = this.char(serviceArg, 'lock_target_state');
      return target ? [this.write(accessoryArg, serviceArg, target, requestArg.service === 'lock' ? 1 : 0)] : [];
    }

    if (requestArg.service === 'set_temperature') {
      const temperature = this.numberValue(requestArg.data?.temperature ?? requestArg.data?.targetTemperature);
      if (temperature === undefined) {
        return [];
      }
      const directTarget = this.char(serviceArg, 'target_temperature');
      if (directTarget) {
        return [this.write(accessoryArg, serviceArg, directTarget, temperature)];
      }
      const mode = this.numberValue(this.charValue(serviceArg, 'target_heater_cooler_state'));
      const threshold = mode === 2 ? this.char(serviceArg, 'cooling_threshold_temperature') : this.char(serviceArg, 'heating_threshold_temperature');
      return threshold ? [this.write(accessoryArg, serviceArg, threshold, temperature)] : [];
    }

    if (requestArg.service === 'set_hvac_mode') {
      const mode = this.stringValue(requestArg.data?.hvacMode ?? requestArg.data?.hvac_mode ?? requestArg.data?.mode)?.toLowerCase();
      if (!mode) {
        return [];
      }
      if (serviceTypeArg === 'thermostat') {
        const values: Record<string, number> = { off: 0, heat: 1, cool: 2, heat_cool: 3, auto: 3 };
        const target = this.char(serviceArg, 'heating_cooling_target');
        return target && values[mode] !== undefined ? [this.write(accessoryArg, serviceArg, target, values[mode])] : [];
      }
      if (serviceTypeArg === 'heater_cooler') {
        const active = this.char(serviceArg, 'active');
        if (mode === 'off') {
          return active ? [this.write(accessoryArg, serviceArg, active, 0)] : [];
        }
        const values: Record<string, number> = { heat_cool: 0, auto: 0, heat: 1, cool: 2 };
        const target = this.char(serviceArg, 'target_heater_cooler_state');
        const writes: IHomekitCharacteristicWrite[] = [];
        if (active) {
          writes.push(this.write(accessoryArg, serviceArg, active, 1));
        }
        if (target && values[mode] !== undefined) {
          writes.push(this.write(accessoryArg, serviceArg, target, values[mode]));
        }
        return writes;
      }
    }

    if (requestArg.service === 'set_value') {
      const value = requestArg.data?.value;
      const requestedType = this.stringValue(requestArg.data?.characteristicType || requestArg.data?.type);
      const char = requestedType ? this.charByType(serviceArg, requestedType) : this.primaryWritableCharacteristic(serviceArg, serviceTypeArg, value);
      return value !== undefined && char ? [this.write(accessoryArg, serviceArg, char, value)] : [];
    }

    return [];
  }

  private static findTargetService(snapshotArg: IHomekitControllerSnapshot, requestArg: IServiceCallRequest): { accessory: IHomekitAccessory; service: IHomekitService } | undefined {
    const mapped = this.mappedServices(snapshotArg);
    if (requestArg.target.entityId) {
      const entity = this.toEntities(snapshotArg).find((entityArg) => entityArg.id === requestArg.target.entityId || entityArg.uniqueId === requestArg.target.entityId);
      const aid = this.numberValue(entity?.attributes?.aid);
      const serviceIid = this.numberValue(entity?.attributes?.serviceIid);
      return aid !== undefined && serviceIid !== undefined ? this.accessoryServiceByIid(snapshotArg, aid, serviceIid) : undefined;
    }
    if (requestArg.target.deviceId) {
      return mapped.find((mappedArg) => this.deviceId(snapshotArg, mappedArg.accessory) === requestArg.target.deviceId && String(mappedArg.platform) === requestArg.domain)
        || mapped.find((mappedArg) => this.deviceId(snapshotArg, mappedArg.accessory) === requestArg.target.deviceId);
    }
    return mapped.find((mappedArg) => String(mappedArg.platform) === requestArg.domain) || mapped[0];
  }

  private static findTargetAccessory(snapshotArg: IHomekitControllerSnapshot, requestArg: IServiceCallRequest): IHomekitAccessory | undefined {
    const aid = this.numberValue(requestArg.data?.aid || requestArg.data?.accessoryId);
    if (aid !== undefined) {
      return snapshotArg.accessories.find((accessoryArg) => accessoryArg.aid === aid);
    }
    if (requestArg.target.deviceId) {
      return snapshotArg.accessories.find((accessoryArg) => this.deviceId(snapshotArg, accessoryArg) === requestArg.target.deviceId);
    }
    const target = this.findTargetService(snapshotArg, requestArg);
    return target?.accessory || snapshotArg.accessories[0];
  }

  private static accessoryServiceByIid(snapshotArg: IHomekitControllerSnapshot, aidArg: number, serviceIidArg: number): { accessory: IHomekitAccessory; service: IHomekitService } | undefined {
    const accessory = snapshotArg.accessories.find((accessoryArg) => accessoryArg.aid === aidArg);
    const service = accessory ? this.accessoryServices(accessory).find((serviceArg) => serviceArg.iid === serviceIidArg) : undefined;
    return accessory && service ? { accessory, service } : undefined;
  }

  private static entityState(serviceArg: IHomekitService, serviceTypeArg: TKnownService): unknown {
    if (serviceTypeArg === 'lightbulb' || serviceTypeArg === 'switch' || serviceTypeArg === 'outlet') {
      return this.booleanState(this.charValue(serviceArg, 'on')) ? 'on' : 'off';
    }
    if (serviceTypeArg === 'fan' || serviceTypeArg === 'fan_v2' || serviceTypeArg === 'air_purifier') {
      return this.booleanState(this.charValue(serviceArg, serviceTypeArg === 'fan' ? 'on' : 'active')) ? 'on' : 'off';
    }
    if (serviceTypeArg === 'thermostat') {
      return this.thermostatMode(this.charValue(serviceArg, 'heating_cooling_target'));
    }
    if (serviceTypeArg === 'heater_cooler') {
      return this.numberValue(this.charValue(serviceArg, 'active')) === 0 ? 'off' : this.heaterCoolerMode(this.charValue(serviceArg, 'target_heater_cooler_state'));
    }
    if (serviceTypeArg === 'garage_door_opener') {
      return this.garageDoorState(this.charValue(serviceArg, 'current_door_state'));
    }
    if (serviceTypeArg === 'window' || serviceTypeArg === 'window_covering') {
      return this.coverState(serviceArg);
    }
    if (serviceTypeArg === 'lock_mechanism') {
      return this.lockState(this.charValue(serviceArg, 'lock_current_state'));
    }
    if (this.binarySensorService(serviceTypeArg)) {
      return this.binarySensorState(serviceArg, serviceTypeArg);
    }
    if (serviceTypeArg === 'camera_rtp_stream_management') {
      return this.numberValue(this.charValue(serviceArg, 'active')) === 0 ? 'off' : 'available';
    }
    return this.sensorState(serviceArg, serviceTypeArg);
  }

  private static entityAttributes(accessoryArg: IHomekitAccessory, serviceArg: IHomekitService, serviceTypeArg: TKnownService): Record<string, unknown> {
    const info = this.accessoryInfo(accessoryArg);
    const attributes: Record<string, unknown> = {
      aid: accessoryArg.aid,
      serviceIid: serviceArg.iid,
      serviceType: serviceTypeArg,
      homekitServiceType: serviceArg.type,
      characteristics: this.characteristicValues(serviceArg),
      serialNumber: info.serialNumber,
    };

    const writable = this.primaryWritableCharacteristic(serviceArg, serviceTypeArg);
    if (writable) {
      attributes.writableCharacteristic = { aid: accessoryArg.aid, serviceIid: serviceArg.iid, iid: writable.iid, type: writable.type, characteristicType: this.characteristicType(writable.type) };
    }
    if (serviceTypeArg === 'lightbulb') {
      attributes.brightness = this.charValue(serviceArg, 'brightness');
      attributes.hue = this.charValue(serviceArg, 'hue');
      attributes.saturation = this.charValue(serviceArg, 'saturation');
      attributes.colorTemperature = this.charValue(serviceArg, 'color_temperature');
    }
    if (serviceTypeArg === 'outlet') {
      attributes.outletInUse = this.charValue(serviceArg, 'outlet_in_use');
    }
    if (serviceTypeArg === 'fan' || serviceTypeArg === 'fan_v2' || serviceTypeArg === 'air_purifier') {
      attributes.percentage = this.charValue(serviceArg, 'rotation_speed');
      attributes.rotationDirection = this.charValue(serviceArg, 'rotation_direction');
      attributes.swingMode = this.charValue(serviceArg, 'swing_mode');
    }
    if (serviceTypeArg === 'thermostat' || serviceTypeArg === 'heater_cooler') {
      attributes.currentTemperature = this.charValue(serviceArg, 'current_temperature');
      attributes.targetTemperature = this.charValue(serviceArg, 'target_temperature');
      attributes.targetTemperatureHigh = this.charValue(serviceArg, 'cooling_threshold_temperature');
      attributes.targetTemperatureLow = this.charValue(serviceArg, 'heating_threshold_temperature');
      attributes.currentHumidity = this.charValue(serviceArg, 'current_humidity');
      attributes.targetHumidity = this.charValue(serviceArg, 'target_humidity');
    }
    if (serviceTypeArg === 'window' || serviceTypeArg === 'window_covering') {
      attributes.currentPosition = this.charValue(serviceArg, 'current_position');
      attributes.targetPosition = this.charValue(serviceArg, 'target_position');
      attributes.positionState = this.charValue(serviceArg, 'position_state');
    }
    if (serviceTypeArg === 'garage_door_opener') {
      attributes.obstructionDetected = this.charValue(serviceArg, 'obstruction_detected');
    }
    if (serviceTypeArg === 'battery_service') {
      attributes.unit = '%';
      attributes.lowBattery = this.numberValue(this.charValue(serviceArg, 'status_low_battery')) === 1;
      attributes.chargingState = this.charValue(serviceArg, 'charging_state');
    }
    return attributes;
  }

  private static platformForService(serviceTypeArg: TKnownService): TEntityPlatform | undefined {
    if (serviceTypeArg === 'lightbulb') {
      return 'light';
    }
    if (serviceTypeArg === 'switch' || serviceTypeArg === 'outlet') {
      return 'switch';
    }
    if (serviceTypeArg === 'thermostat' || serviceTypeArg === 'heater_cooler') {
      return 'climate';
    }
    if (serviceTypeArg === 'garage_door_opener' || serviceTypeArg === 'window' || serviceTypeArg === 'window_covering') {
      return 'cover';
    }
    if (serviceTypeArg === 'lock_mechanism') {
      return 'lock' as TEntityPlatform;
    }
    if (serviceTypeArg === 'fan' || serviceTypeArg === 'fan_v2' || serviceTypeArg === 'air_purifier') {
      return 'fan';
    }
    if (serviceTypeArg === 'camera_rtp_stream_management') {
      return 'camera' as TEntityPlatform;
    }
    if (this.binarySensorService(serviceTypeArg)) {
      return 'binary_sensor';
    }
    if (this.sensorService(serviceTypeArg)) {
      return 'sensor';
    }
    return undefined;
  }

  private static capabilityForPlatform(platformArg: TEntityPlatform): plugins.shxInterfaces.data.TDeviceCapability {
    const platform = String(platformArg);
    if (platform === 'light') {
      return 'light';
    }
    if (platform === 'cover') {
      return 'cover';
    }
    if (platform === 'lock') {
      return 'lock';
    }
    if (platform === 'fan') {
      return 'fan';
    }
    if (platform === 'climate') {
      return 'climate';
    }
    if (platform === 'camera') {
      return 'camera';
    }
    if (platform === 'switch') {
      return 'switch';
    }
    return 'sensor';
  }

  private static serviceWritable(serviceArg: IHomekitService, serviceTypeArg: TKnownService): boolean {
    return Boolean(this.primaryWritableCharacteristic(serviceArg, serviceTypeArg));
  }

  private static primaryWritableCharacteristic(serviceArg: IHomekitService, serviceTypeArg: TKnownService, valueArg?: unknown): IHomekitCharacteristic | undefined {
    if (serviceTypeArg === 'lightbulb' && typeof valueArg === 'number') {
      return this.char(serviceArg, 'brightness') || this.char(serviceArg, 'on');
    }
    const types = this.primaryWritableTypes(serviceTypeArg);
    for (const type of types) {
      const char = this.char(serviceArg, type);
      if (char && this.characteristicWritable(char, type)) {
        return char;
      }
    }
    return undefined;
  }

  private static primaryOnCharacteristic(serviceArg: IHomekitService, serviceTypeArg: TKnownService): IHomekitCharacteristic | undefined {
    if (serviceTypeArg === 'fan_v2' || serviceTypeArg === 'air_purifier') {
      return this.char(serviceArg, 'active');
    }
    if (serviceTypeArg === 'fan') {
      return this.char(serviceArg, 'on');
    }
    return this.char(serviceArg, 'on') || this.char(serviceArg, 'active');
  }

  private static primaryWritableTypes(serviceTypeArg: TKnownService): TKnownCharacteristic[] {
    if (serviceTypeArg === 'lightbulb' || serviceTypeArg === 'switch' || serviceTypeArg === 'outlet' || serviceTypeArg === 'fan') {
      return ['on'];
    }
    if (serviceTypeArg === 'fan_v2' || serviceTypeArg === 'air_purifier') {
      return ['active', 'rotation_speed'];
    }
    if (serviceTypeArg === 'thermostat') {
      return ['target_temperature', 'heating_cooling_target'];
    }
    if (serviceTypeArg === 'heater_cooler') {
      return ['active', 'target_heater_cooler_state', 'heating_threshold_temperature', 'cooling_threshold_temperature'];
    }
    if (serviceTypeArg === 'garage_door_opener') {
      return ['target_door_state'];
    }
    if (serviceTypeArg === 'window' || serviceTypeArg === 'window_covering') {
      return ['target_position', 'hold_position'];
    }
    if (serviceTypeArg === 'lock_mechanism') {
      return ['lock_target_state'];
    }
    return [];
  }

  private static accessoryInfo(accessoryArg: IHomekitAccessory): IAccessoryInfo {
    const infoService = this.accessoryServices(accessoryArg).find((serviceArg) => this.serviceType(serviceArg.type) === 'accessory_information');
    const name = this.stringValue(accessoryArg.name)
      || this.stringValue(infoService ? this.charValue(infoService, 'name') : undefined)
      || this.stringValue(accessoryArg.model)
      || `HomeKit accessory ${accessoryArg.aid}`;
    return {
      name,
      manufacturer: this.stringValue(accessoryArg.manufacturer) || this.stringValue(infoService ? this.charValue(infoService, 'manufacturer') : undefined),
      model: this.stringValue(accessoryArg.model) || this.stringValue(infoService ? this.charValue(infoService, 'model') : undefined),
      serialNumber: this.stringValue(accessoryArg.serialNumber) || this.stringValue(accessoryArg.serial_number) || this.stringValue(infoService ? this.charValue(infoService, 'serial_number') : undefined),
      firmwareRevision: this.stringValue(accessoryArg.firmwareRevision) || this.stringValue(accessoryArg.firmware_revision) || this.stringValue(infoService ? this.charValue(infoService, 'firmware_revision') : undefined),
      hardwareRevision: this.stringValue(accessoryArg.hardwareRevision) || this.stringValue(accessoryArg.hardware_revision) || this.stringValue(infoService ? this.charValue(infoService, 'hardware_revision') : undefined),
    };
  }

  private static entityName(accessoryArg: IHomekitAccessory, serviceArg: IHomekitService, serviceTypeArg: TKnownService): string {
    const accessoryName = this.accessoryInfo(accessoryArg).name;
    const serviceName = this.stringValue(serviceArg.name) || this.stringValue(this.charValue(serviceArg, 'name')) || this.serviceTypeName(serviceTypeArg);
    const foldedAccessory = this.foldedName(accessoryName);
    const foldedService = this.foldedName(serviceName);
    if (!serviceName || foldedAccessory === foldedService || foldedAccessory.includes(foldedService) || foldedService.includes(foldedAccessory)) {
      return accessoryName;
    }
    return `${accessoryName} ${serviceName}`;
  }

  private static serviceTypeName(serviceTypeArg: TKnownService): string {
    return serviceTypeArg.split('_').map((partArg) => `${partArg.charAt(0).toUpperCase()}${partArg.slice(1)}`).join(' ');
  }

  private static accessoryServices(accessoryArg: IHomekitAccessory): IHomekitService[] {
    if (Array.isArray(accessoryArg.services)) {
      return accessoryArg.services;
    }
    if (accessoryArg.services && typeof accessoryArg.services === 'object') {
      return Object.values(accessoryArg.services);
    }
    return [];
  }

  private static serviceCharacteristics(serviceArg: IHomekitService): IHomekitCharacteristic[] {
    if (Array.isArray(serviceArg.characteristics)) {
      return serviceArg.characteristics;
    }
    if (serviceArg.characteristics && typeof serviceArg.characteristics === 'object') {
      return Object.values(serviceArg.characteristics);
    }
    if (serviceArg.characteristicsByType && typeof serviceArg.characteristicsByType === 'object') {
      return Object.values(serviceArg.characteristicsByType);
    }
    if (serviceArg.characteristics_by_type && typeof serviceArg.characteristics_by_type === 'object') {
      return Object.values(serviceArg.characteristics_by_type);
    }
    return [];
  }

  private static char(serviceArg: IHomekitService, characteristicTypeArg: TKnownCharacteristic): IHomekitCharacteristic | undefined {
    return this.serviceCharacteristics(serviceArg).find((charArg) => this.characteristicType(charArg.type) === characteristicTypeArg);
  }

  private static charByType(serviceArg: IHomekitService, typeArg: string): IHomekitCharacteristic | undefined {
    const characteristicType = this.characteristicType(typeArg);
    return characteristicType === 'unknown'
      ? this.serviceCharacteristics(serviceArg).find((charArg) => charArg.type === typeArg)
      : this.char(serviceArg, characteristicType);
  }

  private static charValue(serviceArg: IHomekitService, characteristicTypeArg: TKnownCharacteristic): unknown {
    return this.char(serviceArg, characteristicTypeArg)?.value;
  }

  private static characteristicValues(serviceArg: IHomekitService): Record<string, unknown> {
    const values: Record<string, unknown> = {};
    for (const char of this.serviceCharacteristics(serviceArg)) {
      const type = this.characteristicType(char.type);
      values[type === 'unknown' ? char.type : type] = char.value;
    }
    return values;
  }

  private static characteristicWritable(charArg: IHomekitCharacteristic, typeArg = this.characteristicType(charArg.type)): boolean {
    if (Array.isArray(charArg.perms)) {
      return charArg.perms.some((permArg) => ['pw', 'write', 'paired_write', 'write_response'].includes(permArg.toLowerCase()));
    }
    return writableCharacteristics.has(typeArg);
  }

  private static serviceHasValues(serviceArg: IHomekitService): boolean {
    return this.serviceCharacteristics(serviceArg).some((charArg) => charArg.value !== undefined && charArg.available !== false);
  }

  private static binarySensorService(serviceTypeArg: TKnownService): boolean {
    return ['carbon_monoxide_sensor', 'contact_sensor', 'leak_sensor', 'motion_sensor', 'occupancy_sensor', 'smoke_sensor'].includes(serviceTypeArg);
  }

  private static sensorService(serviceTypeArg: TKnownService): boolean {
    return ['air_quality_sensor', 'battery_service', 'carbon_dioxide_sensor', 'humidity_sensor', 'light_sensor', 'temperature_sensor'].includes(serviceTypeArg);
  }

  private static binarySensorState(serviceArg: IHomekitService, serviceTypeArg: TKnownService): boolean | undefined {
    if (serviceTypeArg === 'contact_sensor') {
      const value = this.numberValue(this.charValue(serviceArg, 'contact_state'));
      return value === undefined ? undefined : value === 1;
    }
    if (serviceTypeArg === 'motion_sensor') {
      return this.booleanState(this.charValue(serviceArg, 'motion_detected'));
    }
    if (serviceTypeArg === 'smoke_sensor') {
      return this.numberValue(this.charValue(serviceArg, 'smoke_detected')) === 1;
    }
    if (serviceTypeArg === 'carbon_monoxide_sensor') {
      return this.numberValue(this.charValue(serviceArg, 'carbon_monoxide_detected')) === 1;
    }
    if (serviceTypeArg === 'carbon_dioxide_sensor') {
      return this.numberValue(this.charValue(serviceArg, 'carbon_dioxide_detected')) === 1;
    }
    if (serviceTypeArg === 'leak_sensor') {
      return this.numberValue(this.charValue(serviceArg, 'leak_detected')) === 1;
    }
    if (serviceTypeArg === 'occupancy_sensor') {
      return this.numberValue(this.charValue(serviceArg, 'occupancy_detected')) === 1;
    }
    return undefined;
  }

  private static sensorState(serviceArg: IHomekitService, serviceTypeArg: TKnownService): unknown {
    if (serviceTypeArg === 'temperature_sensor') {
      return this.charValue(serviceArg, 'current_temperature');
    }
    if (serviceTypeArg === 'humidity_sensor') {
      return this.charValue(serviceArg, 'current_humidity');
    }
    if (serviceTypeArg === 'light_sensor') {
      return this.charValue(serviceArg, 'current_light_level');
    }
    if (serviceTypeArg === 'carbon_dioxide_sensor') {
      return this.charValue(serviceArg, 'carbon_dioxide_level') ?? this.binarySensorState(serviceArg, serviceTypeArg);
    }
    if (serviceTypeArg === 'battery_service') {
      return this.charValue(serviceArg, 'battery_level') ?? (this.numberValue(this.charValue(serviceArg, 'status_low_battery')) === 1 ? 'low' : 'normal');
    }
    if (serviceTypeArg === 'air_quality_sensor') {
      return this.airQualityState(this.charValue(serviceArg, 'air_quality'));
    }
    return 'unknown';
  }

  private static thermostatMode(valueArg: unknown): string {
    const modes: Record<number, string> = { 0: 'off', 1: 'heat', 2: 'cool', 3: 'heat_cool' };
    const value = this.numberValue(valueArg);
    return value === undefined ? 'unknown' : modes[value] || 'unknown';
  }

  private static heaterCoolerMode(valueArg: unknown): string {
    const modes: Record<number, string> = { 0: 'heat_cool', 1: 'heat', 2: 'cool' };
    const value = this.numberValue(valueArg);
    return value === undefined ? 'unknown' : modes[value] || 'unknown';
  }

  private static garageDoorState(valueArg: unknown): string {
    const states: Record<number, string> = { 0: 'open', 1: 'closed', 2: 'opening', 3: 'closing', 4: 'stopped' };
    const value = this.numberValue(valueArg);
    return value === undefined ? 'unknown' : states[value] || 'unknown';
  }

  private static coverState(serviceArg: IHomekitService): string {
    const position = this.numberValue(this.charValue(serviceArg, 'current_position'));
    const positionState = this.numberValue(this.charValue(serviceArg, 'position_state'));
    if (positionState === 0) {
      return 'closing';
    }
    if (positionState === 1) {
      return 'opening';
    }
    if (position === 0) {
      return 'closed';
    }
    if (position !== undefined) {
      return 'open';
    }
    return 'unknown';
  }

  private static lockState(valueArg: unknown): string {
    const states: Record<number, string> = { 0: 'unlocked', 1: 'locked', 2: 'jammed', 3: 'unknown' };
    const value = this.numberValue(valueArg);
    return value === undefined ? 'unknown' : states[value] || 'unknown';
  }

  private static airQualityState(valueArg: unknown): string {
    const states: Record<number, string> = { 0: 'unknown', 1: 'excellent', 2: 'good', 3: 'fair', 4: 'inferior', 5: 'poor' };
    const value = this.numberValue(valueArg);
    return value === undefined ? 'unknown' : states[value] || 'unknown';
  }

  private static referencesFromData(dataArg: Record<string, unknown> | undefined): IHomekitCharacteristicReference[] {
    const list = dataArg?.characteristics;
    if (Array.isArray(list)) {
      return list.map((itemArg) => this.referenceFromRecord(itemArg)).filter((itemArg): itemArg is IHomekitCharacteristicReference => Boolean(itemArg));
    }
    const reference = this.referenceFromRecord(dataArg);
    return reference ? [reference] : [];
  }

  private static writesFromData(dataArg: Record<string, unknown> | undefined): IHomekitCharacteristicWrite[] {
    const list = dataArg?.characteristics;
    if (Array.isArray(list)) {
      return list.map((itemArg) => this.writeFromRecord(itemArg)).filter((itemArg): itemArg is IHomekitCharacteristicWrite => Boolean(itemArg));
    }
    const write = this.writeFromRecord(dataArg);
    return write ? [write] : [];
  }

  private static referenceFromRecord(valueArg: unknown): IHomekitCharacteristicReference | undefined {
    if (!this.isRecord(valueArg)) {
      return undefined;
    }
    const aid = this.numberValue(valueArg.aid ?? valueArg.accessoryId);
    const iid = this.numberValue(valueArg.iid ?? valueArg.instanceId);
    if (aid === undefined || iid === undefined) {
      return undefined;
    }
    return {
      aid,
      iid,
      type: this.stringValue(valueArg.type ?? valueArg.characteristicType),
      serviceIid: this.numberValue(valueArg.serviceIid),
      serviceType: this.stringValue(valueArg.serviceType),
    };
  }

  private static writeFromRecord(valueArg: unknown): IHomekitCharacteristicWrite | undefined {
    if (!this.isRecord(valueArg) || !('value' in valueArg)) {
      return undefined;
    }
    const reference = this.referenceFromRecord(valueArg);
    return reference ? { ...reference, value: valueArg.value } : undefined;
  }

  private static write(accessoryArg: IHomekitAccessory, serviceArg: IHomekitService, charArg: IHomekitCharacteristic, valueArg: unknown): IHomekitCharacteristicWrite {
    return {
      aid: accessoryArg.aid,
      serviceIid: serviceArg.iid,
      serviceType: serviceArg.type,
      iid: charArg.iid,
      type: charArg.type,
      value: valueArg,
    };
  }

  private static deviceId(snapshotArg: IHomekitControllerSnapshot, accessoryArg: IHomekitAccessory): string {
    return `homekit_controller.accessory.${this.slug(`${snapshotArg.id || snapshotArg.pairingData?.AccessoryPairingID || 'snapshot'}_${accessoryArg.aid}`)}`;
  }

  private static typeToken(valueArg?: string): string {
    const value = (valueArg || '').trim().toLowerCase();
    const uuidMatch = /^([0-9a-f]{8})-0000-1000-8000-0026bb765291$/.exec(value);
    if (uuidMatch) {
      return uuidMatch[1];
    }
    if (/^[0-9a-f]{1,8}$/.test(value)) {
      return value.padStart(8, '0');
    }
    return value.replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
  }

  private static booleanState(valueArg: unknown): boolean {
    if (typeof valueArg === 'boolean') {
      return valueArg;
    }
    if (typeof valueArg === 'number') {
      return valueArg !== 0;
    }
    if (typeof valueArg === 'string') {
      return ['1', 'true', 'on', 'active'].includes(valueArg.toLowerCase());
    }
    return false;
  }

  private static deviceStateValue(valueArg: unknown): plugins.shxInterfaces.data.TDeviceStateValue {
    if (Array.isArray(valueArg)) {
      return JSON.stringify(valueArg);
    }
    if (typeof valueArg === 'string' || typeof valueArg === 'number' || typeof valueArg === 'boolean' || valueArg === null || this.isRecord(valueArg)) {
      return valueArg;
    }
    return valueArg === undefined ? null : String(valueArg);
  }

  private static stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }

  private static numberValue(valueArg: unknown): number | undefined {
    if (typeof valueArg === 'number' && Number.isFinite(valueArg)) {
      return valueArg;
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const value = Number(valueArg);
      return Number.isFinite(value) ? value : undefined;
    }
    return undefined;
  }

  private static brightnessValue(dataArg?: Record<string, unknown>): number | undefined {
    const percentage = this.numberValue(dataArg?.brightnessPct ?? dataArg?.brightnessPercentage ?? dataArg?.brightness_percentage ?? dataArg?.percentage);
    if (percentage !== undefined) {
      return this.clampPercent(percentage);
    }
    const brightness = this.numberValue(dataArg?.brightness);
    return brightness === undefined ? undefined : this.clampPercent(Math.round(brightness * 100 / 255));
  }

  private static clampPercent(valueArg: number): number {
    return Math.max(0, Math.min(100, valueArg));
  }

  private static isRecord(valueArg: unknown): valueArg is Record<string, unknown> {
    return typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg);
  }

  private static foldedName(valueArg: string): string {
    return valueArg.toLowerCase().replace(/\s+/g, '');
  }

  private static slug(valueArg: string): string {
    return valueArg.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'homekit_controller';
  }
}
