import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationEvent, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { DsmrClient } from './dsmr.classes.client.js';
import { DsmrConfigFlow } from './dsmr.classes.configflow.js';
import { createDsmrDiscoveryDescriptor } from './dsmr.discovery.js';
import { DsmrMapper } from './dsmr.mapper.js';
import type { IDsmrConfig } from './dsmr.types.js';
import { dsmrDomain } from './dsmr.types.js';

export class DsmrIntegration extends BaseIntegration<IDsmrConfig> {
  public readonly domain = dsmrDomain;
  public readonly displayName = 'DSMR Smart Meter';
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createDsmrDiscoveryDescriptor();
  public readonly configFlow = new DsmrConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/dsmr',
    upstreamDomain: dsmrDomain,
    integrationType: 'hub',
    iotClass: 'local_push',
    requirements: ['dsmr-parser==1.5.0'],
    dependencies: ['usb'],
    afterDependencies: [],
    codeowners: ['@Robbie1221'],
    documentation: 'https://www.home-assistant.io/integrations/dsmr',
    configFlow: true,
    discovery: {
      manual: ['serial', 'network'],
      usb: 'Configuration supports explicit serial paths; no USB/serial probing is performed here.',
      note: 'Manual serial/network setup is supported. Live serial transport is not faked; use snapshot, telegram, telegramProvider, or liveRead network refresh.',
    },
    runtime: {
      type: 'read-only-runtime',
      mode: 'DSMR telegram/status snapshot mapping',
      entities: ['sensor'],
      services: ['refresh'],
    },
    localApi: {
      implemented: [
        'manual DSMR serial and network meter configuration',
        'native DSMR P1 telegram parsing for common energy, gas, power, voltage, current, and diagnostic sensors',
        'status/snapshot mapping to Home Assistant-style sensor entities',
        'network telegram refresh when explicitly enabled with liveRead',
      ],
      explicitUnsupported: [
        'fake live serial hardware success without a telegram source',
        'native serial port transport without an injected telegramProvider',
        'Home Assistant entity registry migrations',
      ],
    },
  };

  public async setup(configArg: IDsmrConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new DsmrRuntime(new DsmrClient(configArg));
  }

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

export class HomeAssistantDsmrIntegration extends DsmrIntegration {}

class DsmrRuntime implements IIntegrationRuntime {
  public domain = dsmrDomain;

  constructor(private readonly client: DsmrClient) {}

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

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

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    const unsubscribe = this.client.onEvent((eventArg) => handlerArg(DsmrMapper.toIntegrationEvent(eventArg)));
    return async () => unsubscribe();
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain === dsmrDomain && ['refresh', 'reload'].includes(requestArg.service)) {
      const result = await this.client.refresh();
      return { success: result.success, error: result.error, data: result.snapshot || result.data };
    }
    return { success: false, error: `Unsupported DSMR service: ${requestArg.domain}.${requestArg.service}` };
  }

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