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 { GlancesClient } from './glances.classes.client.js';
import { GlancesConfigFlow } from './glances.classes.configflow.js';
import { createGlancesDiscoveryDescriptor } from './glances.discovery.js';
import { GlancesMapper } from './glances.mapper.js';
import type { IGlancesConfig } from './glances.types.js';
import { glancesDomain } from './glances.types.js';

export class GlancesIntegration extends BaseIntegration<IGlancesConfig> {
  public readonly domain = glancesDomain;
  public readonly displayName = 'Glances';
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createGlancesDiscoveryDescriptor();
  public readonly configFlow = new GlancesConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/glances',
    upstreamDomain: glancesDomain,
    integrationType: 'service',
    iotClass: 'local_polling',
    requirements: ['glances-api==0.10.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@engrbm87'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/glances',
    discovery: {
      manual: true,
      http: 'Manual local HTTP endpoint candidates are recognized; no active LAN scan is performed.',
      note: 'Glances has no HA automatic discovery. Configure host/port or provide raw /api/{version}/all data, HA sensor data, or a snapshot.',
    },
    runtime: {
      type: 'read-only-runtime',
      polling: 'local HTTP Glances REST API /api/{version}/all',
      services: ['snapshot', 'status', 'refresh'],
      controls: false,
    },
    localApi: {
      implemented: [
        'Glances REST API v4/v3 probing against /api/{version}/all',
        'native mapping compatible with glances-api get_ha_sensor_data for CPU, memory, disk, network, load, temperature, process, container, GPU, and RAID sensors',
        'manual raw API data, HA sensor data, and snapshot inputs',
        'read-only refresh service',
      ],
      explicitUnsupported: [
        'Home Assistant Python glances_api compatibility wrapper',
        'write/control services',
        'fake live API success without a configured HTTP endpoint or snapshot/manual data',
      ],
    },
  };

  public async setup(configArg: IGlancesConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new GlancesRuntime(new GlancesClient(configArg));
  }

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

export class HomeAssistantGlancesIntegration extends GlancesIntegration {}

class GlancesRuntime implements IIntegrationRuntime {
  public domain = glancesDomain;

  constructor(private readonly client: GlancesClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain !== glancesDomain) {
      return { success: false, error: `Unsupported Glances service domain: ${requestArg.domain}` };
    }
    if (requestArg.service === 'snapshot' || requestArg.service === 'status') {
      return { success: true, data: await this.client.getSnapshot() };
    }
    if (requestArg.service === 'refresh' || requestArg.service === 'reload') {
      const result = await this.client.refresh();
      return { success: result.success, error: result.error, data: result.snapshot || result.data };
    }
    return { success: false, error: `Unsupported Glances service: ${requestArg.service}` };
  }

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