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 { BondClient } from './bond.classes.client.js';
import { BondConfigFlow } from './bond.classes.configflow.js';
import { createBondDiscoveryDescriptor } from './bond.discovery.js';
import { BondMapper } from './bond.mapper.js';
import type { IBondConfig } from './bond.types.js';
import { bondDefaultPort, bondDhcpMacPrefixes, bondDisplayName, bondDomain, bondZeroconfType } from './bond.types.js';

export class BondIntegration extends BaseIntegration<IBondConfig> {
  public readonly domain = bondDomain;
  public readonly displayName = bondDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createBondDiscoveryDescriptor();
  public readonly configFlow = new BondConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/bond',
    upstreamDomain: bondDomain,
    integrationType: 'hub',
    iotClass: 'local_push',
    requirements: ['bond-async==0.2.1'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@bdraco', '@prystupa', '@joshs85', '@marciogranzotto'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/bond',
    zeroconf: [bondZeroconfType],
    dhcp: [
      { hostname: 'bond-*', macaddress: `${bondDhcpMacPrefixes[0]}*` },
      { hostname: 'bond-*', macaddress: `${bondDhcpMacPrefixes[1]}*` },
    ],
    discovery: {
      zeroconf: bondZeroconfType,
      dhcp: 'bond-* leases with 3C6A2C1* or F44E38* MAC prefixes',
      manual: true,
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local Bond Bridge HTTP /v2 snapshots with BPUP-compatible local_push modeling',
      services: ['snapshot', 'status', 'refresh', 'fan', 'light', 'cover', 'switch', 'button', 'raw Bond action', 'state belief patch'],
      controls: true,
    },
    localApi: {
      implemented: [
        'GET /v2/sys/version',
        'GET /v2/token during setup-window token discovery',
        'GET /v2/bridge when available',
        'GET /v2/devices and per-device attrs/properties/state snapshots',
        'PUT /v2/devices/{device_id}/actions/{action}',
        'PATCH /v2/devices/{device_id}/state for tracked-state belief updates',
        'snapshot/manual-data and injected client/executor operation',
      ],
      explicitUnsupported: [
        'cloud Bond account APIs',
        'pretending service calls succeeded without host/token, injected client.execute, or commandExecutor',
        'native BPUP UDP subscription sockets in this runtime layer; snapshots stay HTTP/manual/client based',
      ],
    },
  };

  public async setup(configArg: IBondConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new BondRuntime(new BondClient({ port: bondDefaultPort, ...configArg }));
  }

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

export class HomeAssistantBondIntegration extends BondIntegration {}

class BondRuntime implements IIntegrationRuntime {
  public domain = bondDomain;

  constructor(private readonly client: BondClient) {}

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

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

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