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 { BoschShcClient } from './bosch_shc.classes.client.js';
import { BoschShcConfigFlow } from './bosch_shc.classes.configflow.js';
import { createBoschShcDiscoveryDescriptor } from './bosch_shc.discovery.js';
import { BoschShcMapper } from './bosch_shc.mapper.js';
import type { IBoschShcConfig, IBoschShcPairClientRequest } from './bosch_shc.types.js';

export class BoschShcIntegration extends BaseIntegration<IBoschShcConfig> {
  public readonly domain = 'bosch_shc';
  public readonly displayName = 'Bosch SHC';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createBoschShcDiscoveryDescriptor();
  public readonly configFlow = new BoschShcConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/bosch_shc',
    upstreamDomain: 'bosch_shc',
    documentation: 'https://www.home-assistant.io/integrations/bosch_shc',
    integrationType: 'hub',
    iotClass: 'local_push',
    requirements: ['boschshcpy==0.2.107'],
    dependencies: [] as string[],
    afterDependencies: ['zeroconf'],
    codeowners: ['@tschamm'],
    zeroconf: [{ name: 'bosch shc*', type: '_http._tcp.local.' }],
    nativeLiveTransportImplemented: false,
  };

  public async setup(configArg: IBoschShcConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new BoschShcRuntime(new BoschShcClient(configArg));
  }

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

export class HomeAssistantBoschShcIntegration extends BoschShcIntegration {}

class BoschShcRuntime implements IIntegrationRuntime {
  public domain = 'bosch_shc';

  constructor(private readonly client: BoschShcClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === 'bosch_shc') {
        return await this.callBoschService(requestArg);
      }

      const snapshot = await this.client.getSnapshot();
      const command = BoschShcMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported Bosch SHC service mapping: ${requestArg.domain}.${requestArg.service}` };
      }
      if ('error' in command) {
        return { success: false, error: command.error };
      }
      const data = await this.client.executeCommand(command, snapshot);
      return { success: true, data };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : String(error) };
    }
  }

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

  private async callBoschService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (!['pair_client', 'register_client'].includes(requestArg.service)) {
      return { success: false, error: `Unsupported Bosch SHC integration service: ${requestArg.service}` };
    }
    const systemPassword = requestArg.data?.system_password || requestArg.data?.password;
    if (typeof systemPassword !== 'string' || !systemPassword) {
      return { success: false, error: 'Bosch SHC pairing requires data.system_password.' };
    }
    const request: IBoschShcPairClientRequest = {
      systemPassword,
      clientId: typeof requestArg.data?.client_id === 'string' ? requestArg.data.client_id : undefined,
      clientName: typeof requestArg.data?.client_name === 'string' ? requestArg.data.client_name : undefined,
      certificatePem: typeof requestArg.data?.certificate_pem === 'string' ? requestArg.data.certificate_pem : undefined,
    };
    const data = await this.client.pairClient(request);
    return { success: true, data };
  }
}
