import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { SimpleLocalMapper, type IIntegrationEntity, type ISimpleLocalEntitySnapshot, type ISimpleLocalSnapshot, type ISimpleLocalSnapshotOptions, type TSimpleLocalRawData } from '../../core/index.js';
import type { IHikvisioncamConfig } from './hikvisioncam.types.js';
import { hikvisioncamDefaultPort, hikvisioncamProfile } from './hikvisioncam.types.js';

export class HikvisioncamMapper {
  public static toSnapshot(optionsArg: Omit<ISimpleLocalSnapshotOptions<IHikvisioncamConfig>, 'profile'>): ISimpleLocalSnapshot {
    return SimpleLocalMapper.toSnapshot({
      ...optionsArg,
      profile: hikvisioncamProfile,
      rawData: this.normalizeRawData(optionsArg.config, optionsArg.rawData),
    });
  }

  public static toSnapshotFromRaw(configArg: IHikvisioncamConfig, rawDataArg: TSimpleLocalRawData): ISimpleLocalSnapshot {
    return this.toSnapshot({ config: configArg, rawData: rawDataArg, online: true, source: 'manual' });
  }

  public static toDevices(snapshotArg: ISimpleLocalSnapshot): shxInterfaces.data.IDeviceDefinition[] {
    return SimpleLocalMapper.toDevices(hikvisioncamProfile, snapshotArg);
  }

  public static toEntities(snapshotArg: ISimpleLocalSnapshot): IIntegrationEntity[] {
    return SimpleLocalMapper.toEntities(hikvisioncamProfile, snapshotArg);
  }

  public static slug(valueArg: unknown): string {
    return SimpleLocalMapper.slug(valueArg);
  }

  private static normalizeRawData(configArg: IHikvisioncamConfig, rawDataArg: unknown): unknown {
    if (!isRecord(rawDataArg) || ('device' in rawDataArg && 'entities' in rawDataArg)) {
      return rawDataArg;
    }

    const motion = motionValue(rawDataArg);
    if (motion === undefined) {
      return rawDataArg;
    }

    const host = configArg.host || stringValue(rawDataArg.host);
    const port = configArg.port || numberValue(rawDataArg.port) || (host ? hikvisioncamDefaultPort : undefined);
    const name = configArg.name || stringValue(rawDataArg.name) || hikvisioncamProfile.defaultName;
    const entity: ISimpleLocalEntitySnapshot = {
      id: 'motion_detection',
      name: 'Motion Detection',
      platform: 'switch',
      state: motion,
      writable: true,
      attributes: {
        deviceClass: 'switch',
      },
    };

    return {
      device: {
        id: configArg.uniqueId || stringValue(rawDataArg.id) || (host ? `${host}:${port || ''}` : undefined) || name,
        name,
        manufacturer: 'Hikvision',
        model: stringValue(rawDataArg.model) || hikvisioncamProfile.model,
        host,
        port,
        protocol: 'http',
      },
      entities: [entity],
      online: configArg.online ?? true,
      updatedAt: new Date().toISOString(),
      source: 'manual',
      rawData: rawDataArg,
    } satisfies ISimpleLocalSnapshot;
  }
}

const motionValue = (recordArg: Record<string, unknown>): boolean | undefined => booleanValue(recordArg.motionDetectionEnabled ?? recordArg.motion_detection_enabled ?? recordArg.motionDetection ?? recordArg.motion_detection ?? recordArg.isMotionDetectionEnabled ?? recordArg.enabled ?? recordArg.state);

const isRecord = (valueArg: unknown): valueArg is Record<string, unknown> => Boolean(valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg));

const stringValue = (valueArg: unknown): string | undefined => typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;

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

const booleanValue = (valueArg: unknown): boolean | undefined => {
  if (typeof valueArg === 'boolean') {
    return valueArg;
  }
  if (typeof valueArg === 'number') {
    return valueArg !== 0;
  }
  const value = stringValue(valueArg)?.toLowerCase();
  if (!value) {
    return undefined;
  }
  if (['1', 'true', 'yes', 'on', 'enabled'].includes(value)) {
    return true;
  }
  if (['0', 'false', 'no', 'off', 'disabled'].includes(value)) {
    return false;
  }
  return undefined;
};
