import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { SoundtouchClient } from './soundtouch.classes.client.js';
import { SoundtouchConfigFlow } from './soundtouch.classes.configflow.js';
import { createSoundtouchDiscoveryDescriptor } from './soundtouch.discovery.js';
import { SoundtouchMapper } from './soundtouch.mapper.js';
import type { ISoundtouchCommandRequest, ISoundtouchConfig, TSoundtouchCommand } from './soundtouch.types.js';

export class SoundtouchIntegration extends BaseIntegration<ISoundtouchConfig> {
  public readonly domain = 'soundtouch';
  public readonly displayName = 'Bose SoundTouch';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createSoundtouchDiscoveryDescriptor();
  public readonly configFlow = new SoundtouchConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/soundtouch',
    upstreamDomain: 'soundtouch',
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['libsoundtouch==0.8'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@kroimon'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/soundtouch',
    zeroconf: ['_soundtouch._tcp.local.'],
  };

  public async setup(configArg: ISoundtouchConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new SoundtouchRuntime(new SoundtouchClient(configArg));
  }

  public async destroy(): Promise<void> {}
}

export class HomeAssistantSoundtouchIntegration extends SoundtouchIntegration {}

class SoundtouchRuntime implements IIntegrationRuntime {
  public domain = 'soundtouch';

  constructor(private readonly client: SoundtouchClient) {}

  public async devices(): Promise<shxInterfaces.data.IDeviceDefinition[]> {
    return SoundtouchMapper.toDevices(await this.client.getSnapshot());
  }

  public async entities(): Promise<IIntegrationEntity[]> {
    return SoundtouchMapper.toEntities(await this.client.getSnapshot());
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === 'media_player') {
        return await this.callMediaPlayerService(requestArg);
      }
      if (requestArg.domain === 'soundtouch') {
        return await this.callSoundtouchService(requestArg);
      }
      return { success: false, error: `Unsupported SoundTouch service domain: ${requestArg.domain}` };
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

  public async destroy(): Promise<void> {
    await this.client.destroy();
  }

  private async callMediaPlayerService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const command = this.commandFromMediaService(requestArg.service);
    if (!command) {
      return { success: false, error: `Unsupported SoundTouch media_player service: ${requestArg.service}` };
    }
    const result = await this.client.execute(this.commandRequest(command, requestArg));
    return { success: true, data: result };
  }

  private async callSoundtouchService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.service === 'play_preset' || requestArg.service === 'select_preset') {
      const presetId = this.stringData(requestArg, 'preset_id') || this.stringData(requestArg, 'preset') || this.stringData(requestArg, 'presetId') || this.numberStringData(requestArg, 'preset');
      const presetName = this.stringData(requestArg, 'preset_name') || this.stringData(requestArg, 'presetName') || this.stringData(requestArg, 'name');
      const result = await this.client.execute({ command: 'play_preset', presetId, presetName });
      return { success: true, data: result };
    }
    if (requestArg.service === 'play' || requestArg.service === 'pause' || requestArg.service === 'media_play' || requestArg.service === 'media_pause' || requestArg.service === 'volume_set' || requestArg.service === 'volume_mute' || requestArg.service === 'select_source' || requestArg.service === 'play_media') {
      return this.callMediaPlayerService({ ...requestArg, domain: 'media_player' });
    }
    return { success: false, error: `Unsupported SoundTouch service: ${requestArg.service}` };
  }

  private commandFromMediaService(serviceArg: string): TSoundtouchCommand | undefined {
    if (serviceArg === 'turn_on') {
      return 'turn_on';
    }
    if (serviceArg === 'turn_off') {
      return 'turn_off';
    }
    if (serviceArg === 'media_play' || serviceArg === 'play') {
      return 'play';
    }
    if (serviceArg === 'media_pause' || serviceArg === 'pause') {
      return 'pause';
    }
    if (serviceArg === 'media_play_pause' || serviceArg === 'play_pause') {
      return 'play_pause';
    }
    if (serviceArg === 'media_previous_track' || serviceArg === 'previous_track') {
      return 'previous_track';
    }
    if (serviceArg === 'media_next_track' || serviceArg === 'next_track') {
      return 'next_track';
    }
    if (serviceArg === 'volume_up') {
      return 'volume_up';
    }
    if (serviceArg === 'volume_down') {
      return 'volume_down';
    }
    if (serviceArg === 'volume_set' || serviceArg === 'set_volume') {
      return 'set_volume';
    }
    if (serviceArg === 'volume_mute' || serviceArg === 'mute') {
      return 'mute';
    }
    if (serviceArg === 'select_source' || serviceArg === 'select_input') {
      return 'select_source';
    }
    if (serviceArg === 'play_media') {
      return 'play_media';
    }
    return undefined;
  }

  private commandRequest(commandArg: TSoundtouchCommand, requestArg: IServiceCallRequest): ISoundtouchCommandRequest {
    const request: ISoundtouchCommandRequest = { command: commandArg };
    if (commandArg === 'set_volume') {
      request.volumeLevel = this.numberData(requestArg, 'volume_level') ?? this.numberData(requestArg, 'volumeLevel');
      request.volume = this.numberData(requestArg, 'volume');
    }
    if (commandArg === 'mute') {
      request.muted = this.boolData(requestArg, 'is_volume_muted') ?? this.boolData(requestArg, 'mute') ?? this.boolData(requestArg, 'muted');
    }
    if (commandArg === 'select_source') {
      request.source = this.stringData(requestArg, 'source') || this.stringData(requestArg, 'input');
    }
    if (commandArg === 'play_media') {
      request.mediaId = this.stringData(requestArg, 'media_content_id') || this.stringData(requestArg, 'mediaId') || this.stringData(requestArg, 'uri') || this.numberStringData(requestArg, 'media_content_id');
      request.mediaType = this.stringData(requestArg, 'media_content_type') || this.stringData(requestArg, 'mediaType');
      request.url = this.stringData(requestArg, 'url');
      request.presetId = this.stringData(requestArg, 'preset_id') || this.stringData(requestArg, 'presetId') || this.numberStringData(requestArg, 'preset');
      request.presetName = this.stringData(requestArg, 'preset_name') || this.stringData(requestArg, 'presetName');
    }
    return request;
  }

  private stringData(requestArg: IServiceCallRequest, keyArg: string): string | undefined {
    const value = requestArg.data?.[keyArg];
    return typeof value === 'string' && value ? value : undefined;
  }

  private numberData(requestArg: IServiceCallRequest, keyArg: string): number | undefined {
    const value = requestArg.data?.[keyArg];
    return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
  }

  private numberStringData(requestArg: IServiceCallRequest, keyArg: string): string | undefined {
    const value = this.numberData(requestArg, keyArg);
    return typeof value === 'number' ? String(value) : undefined;
  }

  private boolData(requestArg: IServiceCallRequest, keyArg: string): boolean | undefined {
    const value = requestArg.data?.[keyArg];
    return typeof value === 'boolean' ? value : undefined;
  }
}
