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 { YamahaMusiccastClient } from './yamaha_musiccast.classes.client.js';
import { YamahaMusiccastConfigFlow } from './yamaha_musiccast.classes.configflow.js';
import { createYamahaMusiccastDiscoveryDescriptor } from './yamaha_musiccast.discovery.js';
import { YamahaMusiccastMapper } from './yamaha_musiccast.mapper.js';
import type { IYamahaMusiccastCapability, IYamahaMusiccastConfig, IYamahaMusiccastCommandRequest, TYamahaMusiccastCommand, TYamahaMusiccastZoneId } from './yamaha_musiccast.types.js';

export class YamahaMusiccastIntegration extends BaseIntegration<IYamahaMusiccastConfig> {
  public readonly domain = 'yamaha_musiccast';
  public readonly displayName = 'MusicCast';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createYamahaMusiccastDiscoveryDescriptor();
  public readonly configFlow = new YamahaMusiccastConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/yamaha_musiccast',
    upstreamDomain: 'yamaha_musiccast',
    integrationType: 'device',
    iotClass: 'local_push',
    requirements: ['aiomusiccast==0.15.0'],
    dependencies: ['ssdp'],
    afterDependencies: [],
    codeowners: ['@vigonotion', '@micha91'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/yamaha_musiccast',
  };

  public async setup(configArg: IYamahaMusiccastConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new YamahaMusiccastRuntime(new YamahaMusiccastClient(configArg));
  }

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

export class HomeAssistantYamahaMusiccastIntegration extends YamahaMusiccastIntegration {}

class YamahaMusiccastRuntime implements IIntegrationRuntime {
  public domain = 'yamaha_musiccast';

  constructor(private readonly client: YamahaMusiccastClient) {}

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

  public async entities(): Promise<IIntegrationEntity[]> {
    return YamahaMusiccastMapper.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 === 'switch') {
        return await this.callSwitchService(requestArg);
      }
      if (requestArg.domain === 'select') {
        return await this.callSelectService(requestArg);
      }
      if (requestArg.domain === 'number') {
        return await this.callNumberService(requestArg);
      }
      return { success: false, error: `Unsupported Yamaha MusicCast service domain: ${requestArg.domain}` };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : String(error) };
    }
  }

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

  private async callMediaPlayerService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const command = this.commandFromMediaService(requestArg);
    if (!command) {
      return { success: false, error: `Unsupported Yamaha MusicCast media_player service: ${requestArg.service}` };
    }
    const zone = await this.zoneFromRequest(requestArg);
    const result = await this.client.execute({
      command,
      zone,
      source: this.stringData(requestArg, 'source') || this.stringData(requestArg, 'input'),
      soundMode: this.stringData(requestArg, 'sound_mode') || this.stringData(requestArg, 'soundMode'),
      volumeLevel: this.numberData(requestArg, 'volume_level') ?? this.numberData(requestArg, 'volumeLevel'),
      volume: this.numberData(requestArg, 'volume'),
      muted: this.boolData(requestArg, 'is_volume_muted') ?? this.boolData(requestArg, 'mute') ?? this.boolData(requestArg, 'muted'),
      repeat: this.stringData(requestArg, 'repeat'),
      shuffle: this.boolData(requestArg, 'shuffle') ?? this.stringData(requestArg, 'shuffle'),
      option: this.stringData(requestArg, 'option'),
    });
    return { success: true, data: result };
  }

  private async callSwitchService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.service !== 'turn_on' && requestArg.service !== 'turn_off') {
      return { success: false, error: `Unsupported Yamaha MusicCast switch service: ${requestArg.service}` };
    }
    const context = await this.capabilityContextFromRequest(requestArg);
    if (!context.capabilityId) {
      return { success: false, error: 'Yamaha MusicCast switch service requires a capability target.' };
    }
    const result = await this.client.execute({
      command: 'set_switch',
      zone: context.zone,
      capabilityId: context.capabilityId,
      value: requestArg.service === 'turn_on',
    });
    return { success: true, data: result };
  }

  private async callSelectService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.service !== 'select_option') {
      return { success: false, error: `Unsupported Yamaha MusicCast select service: ${requestArg.service}` };
    }
    const context = await this.capabilityContextFromRequest(requestArg);
    const option = this.stringData(requestArg, 'option');
    if (!context.capabilityId || !option) {
      return { success: false, error: 'Yamaha MusicCast select service requires capability target and option.' };
    }
    const result = await this.client.execute({ command: 'select_option', zone: context.zone, capabilityId: context.capabilityId, option, value: option });
    return { success: true, data: result };
  }

  private async callNumberService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.service !== 'set_value' && requestArg.service !== 'set_native_value') {
      return { success: false, error: `Unsupported Yamaha MusicCast number service: ${requestArg.service}` };
    }
    const context = await this.capabilityContextFromRequest(requestArg);
    const value = this.numberData(requestArg, 'value') ?? this.numberData(requestArg, 'native_value') ?? this.numberData(requestArg, 'nativeValue');
    if (!context.capabilityId || typeof value !== 'number') {
      return { success: false, error: 'Yamaha MusicCast number service requires capability target and numeric value.' };
    }
    const result = await this.client.execute({ command: 'set_number', zone: context.zone, capabilityId: context.capabilityId, value });
    return { success: true, data: result };
  }

  private commandFromMediaService(requestArg: IServiceCallRequest): TYamahaMusiccastCommand | undefined {
    if (requestArg.service === 'turn_on') {
      return 'turn_on';
    }
    if (requestArg.service === 'turn_off') {
      return 'turn_off';
    }
    if (requestArg.service === 'volume_up') {
      return 'volume_up';
    }
    if (requestArg.service === 'volume_down') {
      return 'volume_down';
    }
    if (requestArg.service === 'volume_set' || requestArg.service === 'set_volume') {
      return 'set_volume';
    }
    if (requestArg.service === 'volume_mute' || requestArg.service === 'mute') {
      return 'mute';
    }
    if (requestArg.service === 'select_source' || requestArg.service === 'select_input') {
      return 'select_source';
    }
    if (requestArg.service === 'select_sound_mode') {
      return 'select_sound_mode';
    }
    if (requestArg.service === 'media_play' || requestArg.service === 'play') {
      return 'play';
    }
    if (requestArg.service === 'media_pause' || requestArg.service === 'pause') {
      return 'pause';
    }
    if (requestArg.service === 'media_stop' || requestArg.service === 'stop') {
      return 'stop';
    }
    if (requestArg.service === 'media_play_pause' || requestArg.service === 'play_pause') {
      return 'play_pause';
    }
    if (requestArg.service === 'media_previous_track' || requestArg.service === 'previous_track') {
      return 'previous_track';
    }
    if (requestArg.service === 'media_next_track' || requestArg.service === 'next_track') {
      return 'next_track';
    }
    if (requestArg.service === 'repeat_set' || requestArg.service === 'set_repeat') {
      return 'set_repeat';
    }
    if (requestArg.service === 'shuffle_set' || requestArg.service === 'set_shuffle') {
      return 'set_shuffle';
    }
    return undefined;
  }

  private async zoneFromRequest(requestArg: IServiceCallRequest): Promise<TYamahaMusiccastZoneId> {
    const explicit = this.stringData(requestArg, 'zone');
    if (explicit) {
      return explicit;
    }
    const entityId = requestArg.target.entityId;
    if (entityId) {
      const snapshot = await this.client.getSnapshot();
      const entity = YamahaMusiccastMapper.toEntities(snapshot).find((entityArg) => entityArg.id === entityId);
      const zone = entity?.attributes?.zone;
      if (typeof zone === 'string') {
        return zone;
      }
    }
    return 'main';
  }

  private async capabilityContextFromRequest(requestArg: IServiceCallRequest): Promise<{ capabilityId?: string; zone?: TYamahaMusiccastZoneId }> {
    const explicitCapability = this.stringData(requestArg, 'capabilityId') || this.stringData(requestArg, 'capability');
    const explicitZone = this.stringData(requestArg, 'zone');
    if (explicitCapability) {
      return { capabilityId: explicitCapability, zone: explicitZone || 'main' };
    }

    const entityId = requestArg.target.entityId;
    if (entityId) {
      const snapshot = await this.client.getSnapshot();
      const entity = YamahaMusiccastMapper.toEntities(snapshot).find((entityArg) => entityArg.id === entityId);
      const capabilityId = entity?.attributes?.capabilityId;
      const zone = entity?.attributes?.zone;
      if (typeof capabilityId === 'string') {
        return { capabilityId, zone: typeof zone === 'string' ? zone : 'main' };
      }
    }
    return { zone: explicitZone || 'main' };
  }

  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 boolData(requestArg: IServiceCallRequest, keyArg: string): boolean | undefined {
    const value = requestArg.data?.[keyArg];
    return typeof value === 'boolean' ? value : undefined;
  }
}
