import * as plugins from '../../plugins.js';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { MadvrClient } from './madvr.classes.client.js';
import { MadvrConfigFlow } from './madvr.classes.configflow.js';
import { createMadvrDiscoveryDescriptor } from './madvr.discovery.js';
import { MadvrMapper } from './madvr.mapper.js';
import type { IMadvrCommandRequest, IMadvrConfig } from './madvr.types.js';

export class MadvrIntegration extends BaseIntegration<IMadvrConfig> {
  public readonly domain = 'madvr';
  public readonly displayName = 'madVR Envy';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createMadvrDiscoveryDescriptor();
  public readonly configFlow = new MadvrConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/madvr',
    upstreamDomain: 'madvr',
    integrationType: 'device',
    iotClass: 'local_push',
    requirements: ['py-madvr2==1.6.40'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@iloveicedgreentea'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/madvr',
  };

  public async setup(configArg: IMadvrConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new MadvrRuntime(new MadvrClient(configArg));
  }

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

export class HomeAssistantMadvrIntegration extends MadvrIntegration {}

class MadvrRuntime implements IIntegrationRuntime {
  public domain = 'madvr';

  constructor(private readonly client: MadvrClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === 'remote') {
        return await this.callRemoteService(requestArg);
      }
      if (requestArg.domain === 'media_player') {
        return await this.callMediaPlayerService(requestArg);
      }
      if (requestArg.domain === 'button' || requestArg.domain === 'select') {
        return await this.callWritableEntityService(requestArg);
      }
      if (requestArg.domain === 'madvr') {
        return await this.callMadvrService(requestArg);
      }
      return { success: false, error: `Unsupported madVR Envy 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 callRemoteService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.service === 'turn_on') {
      return { success: true, data: await this.client.execute({ command: 'PowerOn', source: 'remote.turn_on', target: requestArg.target }) };
    }
    if (requestArg.service === 'turn_off') {
      return { success: true, data: await this.client.execute({ command: 'PowerOff', source: 'remote.turn_off', target: requestArg.target }) };
    }
    if (requestArg.service !== 'send_command') {
      return { success: false, error: `Unsupported madVR Envy remote service: ${requestArg.service}` };
    }
    const command = requestArg.data?.command;
    if (!command) {
      return { success: false, error: 'madVR Envy remote.send_command requires data.command.' };
    }
    return { success: true, data: await this.client.executeInput(command) };
  }

  private async callMediaPlayerService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.service === 'turn_on') {
      return { success: true, data: await this.client.execute({ command: 'PowerOn', source: 'media_player.turn_on', target: requestArg.target }) };
    }
    if (requestArg.service === 'turn_off') {
      return { success: true, data: await this.client.execute({ command: 'PowerOff', source: 'media_player.turn_off', target: requestArg.target }) };
    }
    return { success: false, error: `Unsupported madVR Envy media_player service: ${requestArg.service}` };
  }

  private async callWritableEntityService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const entity = MadvrMapper.findTargetEntity(snapshot, requestArg);
    if (!entity) {
      return { success: false, error: `madVR Envy ${requestArg.domain}.${requestArg.service} target was not found.` };
    }
    const command = MadvrMapper.commandFromWritableEntity(entity, requestArg);
    if (!command) {
      return { success: false, error: `madVR Envy ${entity.platform} entity is not backed by a command for ${requestArg.service}.` };
    }
    return { success: true, data: await this.client.execute(command) };
  }

  private async callMadvrService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.service === 'send_command' || requestArg.service === 'execute_command') {
      const command = requestArg.data?.command || requestArg.data?.commands;
      if (!command) {
        return { success: false, error: `madVR Envy ${requestArg.service} requires data.command.` };
      }
      return { success: true, data: await this.client.executeInput(command) };
    }

    const command = this.commandForMadvrService(requestArg);
    if (!command) {
      return { success: false, error: `Unsupported madVR Envy service: ${requestArg.service}` };
    }
    return { success: true, data: await this.client.execute(command) };
  }

  private commandForMadvrService(requestArg: IServiceCallRequest): IMadvrCommandRequest | undefined {
    if (requestArg.service === 'standby') {
      return { command: 'Standby', source: 'madvr.standby', target: requestArg.target };
    }
    if (requestArg.service === 'restart') {
      return { command: 'Restart', source: 'madvr.restart', target: requestArg.target };
    }
    if (requestArg.service === 'reload_software') {
      return { command: 'ReloadSoftware', source: 'madvr.reload_software', target: requestArg.target };
    }
    if (requestArg.service === 'hotplug') {
      return { command: 'Hotplug', source: 'madvr.hotplug', target: requestArg.target };
    }
    if (requestArg.service === 'refresh_license_info') {
      return { command: 'RefreshLicenseInfo', source: 'madvr.refresh_license_info', target: requestArg.target };
    }
    if (requestArg.service === 'force_1080p60_output') {
      return { command: 'Force1080p60Output', source: 'madvr.force_1080p60_output', target: requestArg.target };
    }
    if (requestArg.service === 'open_menu') {
      return { command: 'OpenMenu', args: [this.requiredString(requestArg, 'menu', 'madVR Envy open_menu requires data.menu.')], source: 'madvr.open_menu', target: requestArg.target };
    }
    if (requestArg.service === 'key_press' || requestArg.service === 'key_hold') {
      return { command: requestArg.service === 'key_hold' ? 'KeyHold' : 'KeyPress', args: [this.requiredString(requestArg, 'key', `madVR Envy ${requestArg.service} requires data.key.`)], source: `madvr.${requestArg.service}`, target: requestArg.target };
    }
    if (requestArg.service === 'activate_profile') {
      const group = this.requiredString(requestArg, 'profile_group', 'madVR Envy activate_profile requires data.profile_group.');
      const profileNumber = this.optionalString(requestArg, 'profile_number');
      return { command: 'ActivateProfile', args: profileNumber ? [group, profileNumber] : [group], source: 'madvr.activate_profile', target: requestArg.target };
    }
    if (requestArg.service === 'toggle') {
      return { command: 'Toggle', args: [this.requiredString(requestArg, 'option', 'madVR Envy toggle requires data.option.')], source: 'madvr.toggle', target: requestArg.target };
    }
    return undefined;
  }

  private requiredString(requestArg: IServiceCallRequest, keyArg: string, errorArg: string): string {
    const value = this.optionalString(requestArg, keyArg);
    if (!value) {
      throw new Error(errorArg);
    }
    return value;
  }

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