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 { HomeWizardClient } from './homewizard.classes.client.js';
import { HomeWizardConfigFlow } from './homewizard.classes.configflow.js';
import { createHomeWizardDiscoveryDescriptor } from './homewizard.discovery.js';
import { HomeWizardMapper } from './homewizard.mapper.js';
import type { IHomeWizardConfig } from './homewizard.types.js';
import { homeWizardDefaultHttpPort, homeWizardDefaultHttpsPort, homeWizardDisplayName, homeWizardDomain, homeWizardZeroconfTypes } from './homewizard.types.js';

export class HomeWizardIntegration extends BaseIntegration<IHomeWizardConfig> {
  public readonly domain = homeWizardDomain;
  public readonly displayName = homeWizardDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createHomeWizardDiscoveryDescriptor();
  public readonly configFlow = new HomeWizardConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/homewizard',
    upstreamDomain: homeWizardDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'platinum',
    requirements: ['python-homewizard-energy==10.0.1'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@DCSBL'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/homewizard',
    zeroconf: [...homeWizardZeroconfTypes],
    dhcp: [{ registered_devices: true }],
    discovery: {
      zeroconf: [...homeWizardZeroconfTypes],
      dhcp: 'Home Assistant registered_devices DHCP updates plus HomeWizard Energy hostname hints',
      manual: true,
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local HomeWizard Energy HTTP API snapshots (v1 over HTTP and v2 over HTTPS/HTTP when configured)',
      services: ['snapshot', 'status', 'refresh', 'switches', 'status light brightness', 'battery group mode', 'identify', 'reboot', 'telegram', 'API v2 token request'],
      controls: true,
    },
    localApi: {
      implemented: [
        'zeroconf matching for _hwenergy._tcp.local and _homewizard._tcp.local from the Home Assistant manifest',
        'DHCP registered-device/manual discovery candidates',
        `API v1 GET http://host:${homeWizardDefaultHttpPort}/api and /api/v1/data/system/state/telegram plus PUT /api/v1/state/system/identify`,
        `API v2 GET https://host:${homeWizardDefaultHttpsPort}/api, /api/measurement, /api/system, /api/batteries, /api/telegram plus POST /api/user and PUT /api/system, /api/system/identify, /api/system/reboot, /api/batteries`,
        'static snapshot/raw-data and injected client/executor operation',
      ],
      explicitUnsupported: [
        'cloud HomeWizard account APIs and historical cloud data',
        'API v2 websocket push streaming in this polling runtime layer',
        'pretending service calls succeeded without host/client/commandExecutor',
        'API v2 Energy Socket state control until HomeWizard exposes that endpoint publicly',
      ],
    },
  };

  public async setup(configArg: IHomeWizardConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HomeWizardRuntime(new HomeWizardClient(configArg));
  }

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

export class HomeAssistantHomewizardIntegration extends HomeWizardIntegration {}

class HomeWizardRuntime implements IIntegrationRuntime {
  public domain = homeWizardDomain;

  constructor(private readonly client: HomeWizardClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === homeWizardDomain && (requestArg.service === 'snapshot' || requestArg.service === 'status')) {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.domain === homeWizardDomain && 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 = HomeWizardMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported HomeWizard service or target: ${requestArg.domain}.${requestArg.service}` };
      }
      const data = await this.client.execute(command);
      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();
  }
}
