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 { DaikinClient } from './daikin.classes.client.js';
import { DaikinConfigFlow } from './daikin.classes.configflow.js';
import { createDaikinDiscoveryDescriptor } from './daikin.discovery.js';
import { DaikinMapper } from './daikin.mapper.js';
import type { IDaikinConfig } from './daikin.types.js';
import { daikinDisplayName, daikinDomain } from './daikin.types.js';

export class DaikinIntegration extends BaseIntegration<IDaikinConfig> {
  public readonly domain = daikinDomain;
  public readonly displayName = daikinDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createDaikinDiscoveryDescriptor();
  public readonly configFlow = new DaikinConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/daikin',
    upstreamDomain: daikinDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['pydaikin==2.17.2'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@fredrike'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/daikin',
    zeroconf: ['_dkapi._tcp.local.'],
    discovery: {
      zeroconf: '_dkapi._tcp.local.',
      udp: 'DAIKIN_UDP/common/basic_info broadcast on UDP 30050 from source port 30000.',
      http: 'Manual HTTP candidates for /common/basic_info, /aircon/*, /skyfi/*, and /dsiot/* are recognized.',
      manual: true,
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local Daikin HTTP key/value APIs plus SkyFi and BRP084 dsiot read modeling',
      services: ['snapshot', 'status', 'refresh', 'climate controls', 'power switch', 'zone switch', 'streamer', 'holiday/advanced modes when represented by local endpoints'],
      controls: true,
    },
    localApi: {
      implemented: [
        'BRP069-style key/value local HTTP reads and set_control_info writes',
        'BRP072C register_terminal/API-key request modeling when HTTPS is usable by the runtime',
        'AirBase skyfi-prefixed reads plus zone setting writes',
        'SkyFi password API reads and set.cgi/setzone.cgi writes',
        'BRP084 dsiot snapshot reads',
        'snapshot/manual-data and injected client/executor operation',
      ],
      explicitUnsupported: [
        'BRP084 dsiot control writes without an injected commandExecutor',
        'faking command success for snapshot/manual-only configurations',
        'forcing TLS certificate bypass for BRP072C self-signed devices through Node fetch',
      ],
    },
  };

  public async setup(configArg: IDaikinConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new DaikinRuntime(new DaikinClient(configArg));
  }

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

export class HomeAssistantDaikinIntegration extends DaikinIntegration {}

class DaikinRuntime implements IIntegrationRuntime {
  public domain = daikinDomain;

  constructor(private readonly client: DaikinClient) {}

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

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

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