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 { HunterDouglasPowerViewClient } from './hunterdouglas_powerview.classes.client.js';
import { HunterDouglasPowerViewConfigFlow } from './hunterdouglas_powerview.classes.configflow.js';
import { createHunterDouglasPowerViewDiscoveryDescriptor } from './hunterdouglas_powerview.discovery.js';
import { HunterDouglasPowerViewMapper } from './hunterdouglas_powerview.mapper.js';
import type { IHunterDouglasPowerViewConfig } from './hunterdouglas_powerview.types.js';
import { hunterDouglasPowerViewDefaultPort, hunterDouglasPowerViewDhcpMacPrefix, hunterDouglasPowerViewDisplayName, hunterDouglasPowerViewDomain, hunterDouglasPowerViewZeroconfTypes } from './hunterdouglas_powerview.types.js';

export class HunterDouglasPowerViewIntegration extends BaseIntegration<IHunterDouglasPowerViewConfig> {
  public readonly domain = hunterDouglasPowerViewDomain;
  public readonly displayName = hunterDouglasPowerViewDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createHunterDouglasPowerViewDiscoveryDescriptor();
  public readonly configFlow = new HunterDouglasPowerViewConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/hunterdouglas_powerview',
    upstreamDomain: hunterDouglasPowerViewDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    requirements: ['aiopvapi==3.3.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@bdraco', '@kingy444', '@trullock'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/hunterdouglas_powerview',
    zeroconf: hunterDouglasPowerViewZeroconfTypes,
    dhcp: [
      { registered_devices: true },
      { hostname: 'hunter*', macaddress: `${hunterDouglasPowerViewDhcpMacPrefix}*` },
    ],
    discovery: {
      zeroconf: hunterDouglasPowerViewZeroconfTypes,
      dhcp: 'registered PowerView devices, plus hunter* leases with 002674* MAC prefix',
      manual: true,
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local PowerView Hub HTTP snapshots from /api or /home resources',
      services: ['snapshot', 'status', 'refresh', 'cover open/close/stop/position/tilt', 'scene activation', 'raw local request'],
      controls: true,
    },
    localApi: {
      implemented: [
        'API version detection via /api/fwversion, /gateway/info, and /gateway',
        'Hub snapshots from /api/userdata or /gateway plus /home gateway names',
        'Rooms, scenes, and shades from /api/* legacy resources or /home/* Generation 3 resources',
        'Legacy shade moves through PUT /api/shades/{id}',
        'Generation 3 shade moves through PUT /home/shades/positions?ids={id}',
        'Legacy scene activation through GET /api/scenes?sceneId={id}',
        'Generation 3 scene activation through PUT /home/scenes/{id}/activate',
        'snapshot/manual-data and injected client/executor operation',
      ],
      explicitUnsupported: [
        'cloud PowerView account APIs',
        'faking command success for snapshot/manual-only configurations',
        'full Home Assistant entity split behavior for complex dual-rail/overlapped shades; those are represented as one cover with raw position attributes',
      ],
    },
  };

  public async setup(configArg: IHunterDouglasPowerViewConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HunterDouglasPowerViewRuntime(new HunterDouglasPowerViewClient({ port: hunterDouglasPowerViewDefaultPort, ...configArg }));
  }

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

export class HomeAssistantHunterdouglasPowerviewIntegration extends HunterDouglasPowerViewIntegration {}

class HunterDouglasPowerViewRuntime implements IIntegrationRuntime {
  public domain = hunterDouglasPowerViewDomain;

  constructor(private readonly client: HunterDouglasPowerViewClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === hunterDouglasPowerViewDomain && (requestArg.service === 'snapshot' || requestArg.service === 'status')) {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.domain === hunterDouglasPowerViewDomain && requestArg.service === 'refresh') {
        const result = await this.client.refresh();
        return { success: result.success, error: result.error, data: result.snapshot || result.data };
      }

      const snapshot = await this.client.getSnapshot();
      const command = HunterDouglasPowerViewMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported PowerView service or target: ${requestArg.domain}.${requestArg.service}` };
      }
      const data = await this.client.execute({ ...command, apiVersion: snapshot.hub.apiVersion });
      return { success: true, data: data ?? command };
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

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