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 { CastClient } from './cast.classes.client.js';
import { CastConfigFlow } from './cast.classes.configflow.js';
import { createCastDiscoveryDescriptor } from './cast.discovery.js';
import { CastMapper } from './cast.mapper.js';
import type { ICastConfig } from './cast.types.js';

export class CastIntegration extends BaseIntegration<ICastConfig> {
  public readonly domain = 'cast';
  public readonly displayName = 'Google Cast';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createCastDiscoveryDescriptor();
  public readonly configFlow = new CastConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/cast',
    upstreamDomain: 'cast',
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'unknown',
  };

  public async setup(configArg: ICastConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new CastRuntime(new CastClient(configArg));
  }

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

export class HomeAssistantCastIntegration extends CastIntegration {}

class CastRuntime implements IIntegrationRuntime {
  public domain = 'cast';

  constructor(private readonly client: CastClient) {}

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

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

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

    if (requestArg.domain === 'cast') {
      if (requestArg.service === 'launch_app') {
        const appId = requestArg.data?.app_id;
        if (typeof appId !== 'string' || !appId) {
          return { success: false, error: 'Cast launch_app requires data.app_id.' };
        }
        await this.client.launchApp(appId);
        return { success: true };
      }
      return { success: false, error: `Unsupported Cast service: ${requestArg.service}` };
    }

    if (requestArg.service === 'turn_on') {
      await this.client.turnOn();
      return { success: true };
    }
    if (requestArg.service === 'turn_off') {
      await this.client.turnOff();
      return { success: true };
    }
    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 === 'seek') {
      const position = requestArg.data?.seek_position ?? requestArg.data?.position;
      if (typeof position !== 'number') {
        return { success: false, error: 'Cast seek requires data.seek_position.' };
      }
      await this.client.seek(position);
      return { success: true };
    }
    if (requestArg.service === 'volume_set') {
      const level = requestArg.data?.volume_level;
      if (typeof level !== 'number') {
        return { success: false, error: 'Cast volume_set requires data.volume_level.' };
      }
      await this.client.setVolumeLevel(level);
      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: 'Cast volume_mute requires data.is_volume_muted.' };
      }
      await this.client.setMuted(muted);
      return { success: true };
    }
    if (requestArg.service === 'volume_up' || requestArg.service === 'volume_down') {
      await this.client.stepVolume(requestArg.service === 'volume_up' ? 0.05 : -0.05);
      return { success: true };
    }
    if (requestArg.service === 'select_source') {
      const source = requestArg.data?.source;
      if (typeof source !== 'string' || !source) {
        return { success: false, error: 'Cast select_source requires data.source.' };
      }
      await this.client.launchApp(source);
      return { success: true };
    }
    if (requestArg.service === 'play_media') {
      const mediaId = requestArg.data?.media_content_id ?? requestArg.data?.uri;
      const mediaType = requestArg.data?.media_content_type ?? requestArg.data?.media_type;
      if (typeof mediaId !== 'string' || !mediaId) {
        return { success: false, error: 'Cast play_media requires data.media_content_id or data.uri.' };
      }
      if (mediaType === 'cast') {
        const appData = this.parseAppData(mediaId);
        if (typeof appData.app_id === 'string') {
          await this.client.launchApp(appData.app_id);
          return { success: true };
        }
        return { success: false, error: 'Cast app playback currently supports app_id launch payloads.' };
      }
      await this.client.loadMedia({
        contentId: mediaId,
        contentType: typeof mediaType === 'string' && mediaType ? mediaType : 'video/mp4',
        title: typeof requestArg.data?.title === 'string' ? requestArg.data.title : undefined,
        subtitle: typeof requestArg.data?.subtitle === 'string' ? requestArg.data.subtitle : undefined,
        artist: typeof requestArg.data?.artist === 'string' ? requestArg.data.artist : undefined,
        albumName: typeof requestArg.data?.albumName === 'string' ? requestArg.data.albumName : undefined,
        imageUrl: typeof requestArg.data?.imageUrl === 'string' ? requestArg.data.imageUrl : undefined,
        streamType: mediaType === 'music' || mediaType === 'audio' || mediaType === 'audio/mp3' ? 'LIVE' : 'BUFFERED',
      });
      return { success: true };
    }

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

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

  private parseAppData(valueArg: string): Record<string, unknown> {
    try {
      const parsed = JSON.parse(valueArg) as unknown;
      return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
    } catch {
      return {};
    }
  }
}
