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 { FullyKioskClient } from './fully_kiosk.classes.client.js';
import { FullyKioskConfigFlow } from './fully_kiosk.classes.configflow.js';
import { createFullyKioskDiscoveryDescriptor } from './fully_kiosk.discovery.js';
import { FullyKioskMapper } from './fully_kiosk.mapper.js';
import type { IFullyKioskConfig } from './fully_kiosk.types.js';

export class FullyKioskIntegration extends BaseIntegration<IFullyKioskConfig> {
  public readonly domain = 'fully_kiosk';
  public readonly displayName = 'Fully Kiosk Browser';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createFullyKioskDiscoveryDescriptor();
  public readonly configFlow = new FullyKioskConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/fully_kiosk',
    upstreamDomain: 'fully_kiosk',
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'bronze',
    requirements: ['python-fullykiosk==0.0.15'],
    dependencies: [] as string[],
    afterDependencies: ['mqtt'],
    codeowners: ['@cgarwood'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/fully_kiosk',
    nativePort: {
      discovery: ['manual', 'dhcp'],
      snapshotMapping: true,
      localRestApi: true,
      liveCommandSuccessRequiresHostPasswordClientOrExecutor: true,
      mqttEvents: false,
    },
  };

  public async setup(configArg: IFullyKioskConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new FullyKioskRuntime(new FullyKioskClient(configArg));
  }

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

export class HomeAssistantFullyKioskIntegration extends FullyKioskIntegration {}

class FullyKioskRuntime implements IIntegrationRuntime {
  public domain = 'fully_kiosk';

  constructor(private readonly client: FullyKioskClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === 'fully_kiosk' && (requestArg.service === 'snapshot' || requestArg.service === 'status')) {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.domain === 'fully_kiosk' && requestArg.service === 'refresh') {
        const result = await this.client.refresh();
        return { success: result.success, data: result.snapshot, error: result.error };
      }

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

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