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 { ILocalFileConfig } from './local_file.types.js';
import { localFileDefaultName, localFileProfile } from './local_file.types.js';

export class LocalFileMapper {
  public static toSnapshot(optionsArg: Omit<ISimpleLocalSnapshotOptions<ILocalFileConfig>, 'profile'>): ISimpleLocalSnapshot {
    return SimpleLocalMapper.toSnapshot({
      ...optionsArg,
      profile: localFileProfile,
      rawData: this.normalizeRawData(optionsArg.config, optionsArg.rawData, optionsArg.source),
    });
  }

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

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

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

  private static normalizeRawData(configArg: ILocalFileConfig, rawDataArg: unknown, sourceArg?: ISimpleLocalSnapshotOptions<ILocalFileConfig>['source']): unknown {
    if (isRecord(rawDataArg) && 'device' in rawDataArg && 'entities' in rawDataArg) {
      return rawDataArg;
    }

    const rawObject = isRecord(rawDataArg) ? rawDataArg : undefined;
    const metadata = configArg.metadata || {};
    const filePath = stringValue(configArg.filePath) || stringValue(configArg.file_path) || stringValue(rawObject?.filePath) || stringValue(rawObject?.file_path) || stringValue(metadata.filePath) || stringValue(metadata.file_path);
    const imageBytes = numberValue(rawObject?.imageBytes ?? rawObject?.bytes ?? rawObject?.size);
    if (!filePath && imageBytes === undefined) {
      return rawDataArg;
    }

    const name = configArg.name || stringValue(rawObject?.name) || fileName(filePath) || localFileDefaultName;
    const contentType = stringValue(rawObject?.contentType) || stringValue(rawObject?.content_type);
    const uniqueBase = SimpleLocalMapper.slug(filePath || name);
    const entities: ISimpleLocalEntitySnapshot[] = [{
      id: 'image',
      uniqueId: `${localFileProfile.domain}_${uniqueBase}_image`,
      name: 'Image',
      platform: 'sensor',
      state: imageBytes ?? null,
      available: imageBytes !== undefined || Boolean(filePath),
      writable: false,
      unit: 'B',
      deviceClass: 'data_size',
      attributes: {
        file_path: filePath,
        contentType,
        imageBase64: stringValue(rawObject?.imageBase64),
        updatedAt: stringValue(rawObject?.updatedAt),
      },
    }];

    return {
      device: {
        id: configArg.uniqueId || filePath || name,
        name,
        manufacturer: localFileProfile.manufacturer,
        model: 'Local File Camera',
        protocol: localFileProfile.defaultProtocol,
        attributes: {
          file_path: filePath,
          contentType,
        },
      },
      entities,
      online: configArg.online ?? true,
      updatedAt: stringValue(rawObject?.updatedAt) || new Date().toISOString(),
      source: sourceArg || 'manual',
      rawData: rawDataArg,
    } satisfies ISimpleLocalSnapshot;
  }
}

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

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;
