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 { HyperionClient } from './hyperion.classes.client.js';
import { HyperionConfigFlow } from './hyperion.classes.configflow.js';
import { createHyperionDiscoveryDescriptor } from './hyperion.discovery.js';
import { HyperionMapper } from './hyperion.mapper.js';
import type { IHyperionConfig, IHyperionSnapshot } from './hyperion.types.js';
import { hyperionDisplayName, hyperionDomain, hyperionSsdpManufacturer, hyperionSsdpServiceType } from './hyperion.types.js';

export class HyperionIntegration extends BaseIntegration<IHyperionConfig> {
  public readonly domain = hyperionDomain;
  public readonly displayName = hyperionDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createHyperionDiscoveryDescriptor();
  public readonly configFlow = new HyperionConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/hyperion',
    upstreamDomain: hyperionDomain,
    integrationType: 'hub',
    iotClass: 'local_push',
    requirements: ['hyperion-py==0.7.6'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@dermotduffy'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/hyperion',
    ssdp: [{ manufacturer: hyperionSsdpManufacturer, st: hyperionSsdpServiceType }],
    localApi: {
      implemented: [
        'SSDP and manual discovery for Hyperion JSON API endpoints',
        'local HTTP JSON-RPC, TCP JSON server, and optional global WebSocket JSON-RPC request transports',
        'sysinfo plus serverinfo/getInfo modeled snapshots',
        'color, effect, clear, brightness adjustment, component state, still image snapshot, and raw JSON-RPC commands',
        'snapshot/manual-data and injected client/executor operation',
      ],
      explicitUnsupported: [
        'claiming live command success for static snapshots without host/client/executor transport',
        'Hyperion UI token approval workflow beyond accepting an existing token in config',
        'long-lived WebSocket subscription streaming as a runtime event source',
      ],
    },
  };

  public async setup(configArg: IHyperionConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HyperionRuntime(new HyperionClient(configArg));
  }

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

export class HomeAssistantHyperionIntegration extends HyperionIntegration {}

class HyperionRuntime implements IIntegrationRuntime {
  public domain = hyperionDomain;

  constructor(private readonly client: HyperionClient) {}

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

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

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

      const snapshot = await this.client.getSnapshot();
      const commands = HyperionMapper.commandsForService(snapshot, requestArg);
      if (!commands.length) {
        return { success: false, error: `Unsupported Hyperion service: ${requestArg.domain}.${requestArg.service}` };
      }
      const results: unknown[] = [];
      for (const command of commands) {
        results.push(await this.client.execute(command));
      }
      return { success: true, data: results.length === 1 ? results[0] : results };
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

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