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 { ArcamFmjClient } from './arcam_fmj.classes.client.js';
import { ArcamFmjConfigFlow } from './arcam_fmj.classes.configflow.js';
import { createArcamFmjDiscoveryDescriptor } from './arcam_fmj.discovery.js';
import { ArcamFmjMapper } from './arcam_fmj.mapper.js';
import type { IArcamFmjConfig, IArcamFmjCommandRequest } from './arcam_fmj.types.js';

export class ArcamFmjIntegration extends BaseIntegration<IArcamFmjConfig> {
  public readonly domain = 'arcam_fmj';
  public readonly displayName = 'Arcam FMJ Receivers';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createArcamFmjDiscoveryDescriptor();
  public readonly configFlow = new ArcamFmjConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/arcam_fmj',
    upstreamDomain: 'arcam_fmj',
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['arcam-fmj==1.8.3'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@elupus'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/arcam_fmj',
  };

  public async setup(configArg: IArcamFmjConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new ArcamFmjRuntime(new ArcamFmjClient(configArg));
  }

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

export class HomeAssistantArcamFmjIntegration extends ArcamFmjIntegration {}

class ArcamFmjRuntime implements IIntegrationRuntime {
  public domain = 'arcam_fmj';

  constructor(private readonly client: ArcamFmjClient) {}

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

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

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

    try {
      const command = await this.commandFromService(requestArg);
      if (!command) {
        return { success: false, error: `Unsupported Arcam FMJ media_player service: ${requestArg.service}` };
      }
      return { success: true, data: await this.client.execute(command) };
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

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

  private async commandFromService(requestArg: IServiceCallRequest): Promise<IArcamFmjCommandRequest | undefined> {
    const zone = await this.zoneFromRequest(requestArg);
    if (requestArg.service === 'turn_on') {
      return { command: 'turn_on', zone };
    }
    if (requestArg.service === 'turn_off') {
      return { command: 'turn_off', zone };
    }
    if (requestArg.service === 'volume_up') {
      return { command: 'volume_up', zone };
    }
    if (requestArg.service === 'volume_down') {
      return { command: 'volume_down', zone };
    }
    if (requestArg.service === 'volume_set' || requestArg.service === 'set_volume') {
      const volumeLevel = this.numberData(requestArg, 'volume_level') ?? this.numberData(requestArg, 'volumeLevel');
      const volume = this.numberData(requestArg, 'volume');
      if (typeof volumeLevel !== 'number' && typeof volume !== 'number') {
        throw new Error('Arcam FMJ volume_set requires data.volume_level or data.volume.');
      }
      return { command: 'set_volume', zone, volumeLevel, volume };
    }
    if (requestArg.service === 'volume_mute' || requestArg.service === 'mute') {
      const muted = this.boolData(requestArg, 'is_volume_muted') ?? this.boolData(requestArg, 'mute') ?? this.boolData(requestArg, 'muted');
      if (typeof muted !== 'boolean') {
        throw new Error('Arcam FMJ volume_mute requires data.is_volume_muted.');
      }
      return { command: 'mute', zone, muted };
    }
    if (requestArg.service === 'select_source') {
      const source = this.stringData(requestArg, 'source');
      if (!source) {
        throw new Error('Arcam FMJ select_source requires data.source.');
      }
      return { command: 'select_source', zone, source };
    }
    return undefined;
  }

  private async zoneFromRequest(requestArg: IServiceCallRequest): Promise<number> {
    const explicitZone = this.numberData(requestArg, 'zone') ?? numberFromString(this.stringData(requestArg, 'zone'));
    if (explicitZone) {
      return explicitZone;
    }

    const entityId = requestArg.target.entityId;
    if (entityId) {
      const snapshot = await this.client.getSnapshot().catch(() => undefined);
      const entity = snapshot ? ArcamFmjMapper.toEntities(snapshot).find((entityArg) => entityArg.id === entityId) : undefined;
      const zone = entity?.attributes?.zone;
      if (typeof zone === 'number') {
        return zone;
      }
      const match = /zone[_-]?(\d+)/i.exec(entityId);
      if (match) {
        return Number(match[1]);
      }
    }
    return 1;
  }

  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];
    if (typeof value === 'number' && Number.isFinite(value)) {
      return value;
    }
    if (typeof value === 'string' && value.trim()) {
      const parsed = Number(value);
      return Number.isFinite(parsed) ? parsed : undefined;
    }
    return undefined;
  }

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

const numberFromString = (valueArg: string | undefined): number | undefined => {
  if (!valueArg) {
    return undefined;
  }
  const match = valueArg.match(/\d+/);
  return match ? Number(match[0]) : undefined;
};
