import * as plugins from '../../plugins.js';
import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { SimpleLocalMapper, type IIntegrationEntity, type ISimpleLocalSnapshot, type ISimpleLocalSnapshotOptions, type TSimpleLocalRawData } from '../../core/index.js';
import type { IFolderConfig } from './folder.types.js';
import { folderDefaultFilter, folderDefaultName, folderProfile } from './folder.types.js';

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

  public static toSnapshotFromRaw(configArg: IFolderConfig, 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(folderProfile, snapshotArg);
  }

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

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

  private static normalizeRawData(configArg: IFolderConfig, rawDataArg: unknown): unknown {
    if (isRecord(rawDataArg) && 'device' in rawDataArg && 'entities' in rawDataArg) {
      return rawDataArg;
    }
    const rawObject = isRecord(rawDataArg) ? rawDataArg : undefined;
    if (!rawObject || Array.isArray(rawObject.entities)) {
      return rawDataArg;
    }

    const metadata = configArg.metadata || {};
    const folderPath = stringValue(configArg.folder) || stringValue(configArg.folderPath) || stringValue(configArg.folder_path) || stringValue(configArg.path) || stringValue(rawObject.folder) || stringValue(rawObject.folderPath) || stringValue(rawObject.folder_path) || stringValue(rawObject.path) || stringValue(metadata.folder) || stringValue(metadata.folderPath) || stringValue(metadata.folder_path);
    const filter = stringValue(configArg.filter) || stringValue(rawObject.filter) || stringValue(metadata.filter) || folderDefaultFilter;
    const fileList = stringArray(rawObject.file_list) || stringArray(rawObject.fileList) || stringArray(rawObject.files) || [];
    const numberOfFiles = numberValue(rawObject.number_of_files ?? rawObject.numberOfFiles) ?? fileList.length;
    const bytes = numberValue(rawObject.bytes) ?? bytesFromFiles(rawObject.files) ?? 0;
    const name = configArg.name || stringValue(rawObject.name) || folderName(folderPath) || folderDefaultName;
    const uniqueBase = SimpleLocalMapper.slug(folderPath || name);

    return {
      device: {
        id: configArg.uniqueId || folderPath || name,
        name,
        manufacturer: folderProfile.manufacturer,
        model: folderProfile.model,
        protocol: folderProfile.defaultProtocol,
        attributes: {
          folder: folderPath,
          filter,
        },
      },
      entities: [{
        id: 'folder',
        uniqueId: `${folderProfile.domain}_${uniqueBase}_folder`,
        name: 'Folder',
        platform: 'sensor',
        state: roundMegabytes(bytes),
        available: Boolean(folderPath) || rawDataArg !== undefined,
        writable: false,
        unit: 'MB',
        deviceClass: 'data_size',
        attributes: {
          path: folderPath ? ensureTrailingSeparator(folderPath) : undefined,
          filter,
          number_of_files: numberOfFiles,
          bytes,
          file_list: fileList,
        },
      }],
      online: configArg.online ?? true,
      updatedAt: new Date().toISOString(),
      source: 'manual',
      rawData: rawDataArg,
    } satisfies ISimpleLocalSnapshot;
  }
}

const bytesFromFiles = (valueArg: unknown): number | undefined => {
  if (!Array.isArray(valueArg)) {
    return undefined;
  }
  return valueArg.reduce((sumArg, fileArg) => sumArg + (isRecord(fileArg) ? numberValue(fileArg.bytes ?? fileArg.size) ?? 0 : 0), 0);
};

const roundMegabytes = (bytesArg: number): number => Math.round((bytesArg / 1e6) * 100) / 100;

const ensureTrailingSeparator = (pathArg: string): string => pathArg.endsWith(plugins.path.sep) ? pathArg : `${pathArg}${plugins.path.sep}`;

const folderName = (valueArg: string | undefined): string | undefined => valueArg?.split(/[\\/]/).filter(Boolean).pop();

const stringArray = (valueArg: unknown): string[] | undefined => Array.isArray(valueArg) ? valueArg.filter((itemArg): itemArg is string => typeof itemArg === 'string') : undefined;

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

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;
