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 { ShellyClient } from './shelly.classes.client.js';
import { ShellyConfigFlow } from './shelly.classes.configflow.js';
import { createShellyDiscoveryDescriptor } from './shelly.discovery.js';
import { ShellyMapper } from './shelly.mapper.js';
import type { IShellyConfig } from './shelly.types.js';

export class ShellyIntegration extends BaseIntegration<IShellyConfig> {
  public readonly domain = 'shelly';
  public readonly displayName = 'Shelly';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createShellyDiscoveryDescriptor();
  public readonly configFlow = new ShellyConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/shelly',
    upstreamDomain: 'shelly',
    integrationType: 'device',
    iotClass: 'local_push',
    qualityScale: 'platinum',
  };

  public async setup(configArg: IShellyConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new ShellyRuntime(new ShellyClient(configArg));
  }

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

export class HomeAssistantShellyIntegration extends ShellyIntegration {}

class ShellyRuntime implements IIntegrationRuntime {
  public domain = 'shelly';

  constructor(private readonly client: ShellyClient) {}

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

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

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

    const switchId = this.resolveSwitchId(requestArg.target.entityId, requestArg.target.deviceId);
    if (switchId === undefined) {
      return { success: false, error: 'Shelly switch service calls require a switch entity or device target with a numeric switch id.' };
    }

    if (requestArg.service === 'turn_on') {
      await this.client.setSwitchOutput(switchId, true);
      return { success: true };
    }
    if (requestArg.service === 'turn_off') {
      await this.client.setSwitchOutput(switchId, false);
      return { success: true };
    }

    return { success: false, error: `Unsupported Shelly switch service: ${requestArg.service}` };
  }

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

  private resolveSwitchId(entityIdArg?: string, deviceIdArg?: string): number | undefined {
    const candidate = entityIdArg || deviceIdArg;
    const match = candidate?.match(/(?:switch[_\.]|_)(\d+)$/);
    return match ? Number(match[1]) : undefined;
  }
}
