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 { SonosClient } from './sonos.classes.client.js';
import { SonosConfigFlow } from './sonos.classes.configflow.js';
import { createSonosDiscoveryDescriptor } from './sonos.discovery.js';
import { SonosMapper } from './sonos.mapper.js';
import type { ISonosConfig } from './sonos.types.js';

export class SonosIntegration extends BaseIntegration<ISonosConfig> {
  public readonly domain = 'sonos';
  public readonly displayName = 'Sonos';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createSonosDiscoveryDescriptor();
  public readonly configFlow = new SonosConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/sonos',
    upstreamDomain: 'sonos',
    integrationType: 'hub',
    iotClass: 'local_push',
    qualityScale: 'bronze',
  };

  public async setup(configArg: ISonosConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new SonosRuntime(new SonosClient(configArg));
  }

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

export class HomeAssistantSonosIntegration extends SonosIntegration {}

class SonosRuntime implements IIntegrationRuntime {
  public domain = 'sonos';

  constructor(private readonly client: SonosClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain !== 'media_player') {
      return { success: false, error: `Unsupported Sonos service domain: ${requestArg.domain}` };
    }

    if (requestArg.service === 'play') {
      await this.client.play();
      return { success: true };
    }
    if (requestArg.service === 'pause') {
      await this.client.pause();
      return { success: true };
    }
    if (requestArg.service === 'stop') {
      await this.client.stop();
      return { success: true };
    }
    if (requestArg.service === 'next_track') {
      await this.client.next();
      return { success: true };
    }
    if (requestArg.service === 'previous_track') {
      await this.client.previous();
      return { success: true };
    }
    if (requestArg.service === 'volume_set') {
      const rawVolume = requestArg.data?.volume_level ?? requestArg.data?.volume;
      const volume = typeof rawVolume === 'number' && rawVolume <= 1 ? rawVolume * 100 : rawVolume;
      if (typeof volume !== 'number') {
        return { success: false, error: 'Sonos volume_set requires data.volume_level or data.volume.' };
      }
      await this.client.setVolume(volume);
      return { success: true };
    }
    if (requestArg.service === 'volume_mute') {
      const muted = requestArg.data?.is_volume_muted ?? requestArg.data?.muted;
      if (typeof muted !== 'boolean') {
        return { success: false, error: 'Sonos volume_mute requires data.is_volume_muted or data.muted.' };
      }
      await this.client.setMute(muted);
      return { success: true };
    }
    if (requestArg.service === 'play_media') {
      const uri = requestArg.data?.media_content_id ?? requestArg.data?.uri;
      if (typeof uri !== 'string' || !uri) {
        return { success: false, error: 'Sonos play_media requires data.media_content_id or data.uri.' };
      }
      await this.client.playUri(uri, typeof requestArg.data?.title === 'string' ? requestArg.data.title : undefined);
      return { success: true };
    }

    return { success: false, error: `Unsupported Sonos media_player service: ${requestArg.service}` };
  }

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