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 { HueClient } from './hue.classes.client.js';
import { HueConfigFlow } from './hue.classes.configflow.js';
import { createHueDiscoveryDescriptor } from './hue.discovery.js';
import { HueMapper } from './hue.mapper.js';
import type { IHueConfig } from './hue.types.js';

export class HueIntegration extends BaseIntegration<IHueConfig> {
  public readonly domain = 'hue';
  public readonly displayName = 'Philips Hue';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createHueDiscoveryDescriptor();
  public readonly configFlow = new HueConfigFlow();

  public async setup(configArg: IHueConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    const client = new HueClient(configArg);
    return new HueIntegrationRuntime(client);
  }

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

class HueIntegrationRuntime implements IIntegrationRuntime {
  public domain = 'hue';

  constructor(private readonly client: HueClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain !== 'light') {
      return { success: false, error: `Unsupported Hue service domain: ${requestArg.domain}` };
    }

    const entityId = requestArg.target.entityId;
    if (!entityId) {
      return { success: false, error: 'Hue light service calls require target.entityId.' };
    }

    const lightId = entityId.replace(/^light\./, '');
    if (requestArg.service === 'turn_on') {
      await this.client.setLightState(lightId, {
        on: true,
        brightness: typeof requestArg.data?.brightness === 'number' ? requestArg.data.brightness : undefined,
      });
      return { success: true };
    }

    if (requestArg.service === 'turn_off') {
      await this.client.setLightState(lightId, { on: false });
      return { success: true };
    }

    return { success: false, error: `Unsupported Hue light service: ${requestArg.service}` };
  }

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