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 { ApcupsdClient } from './apcupsd.classes.client.js';
import { ApcupsdConfigFlow } from './apcupsd.classes.configflow.js';
import { createApcupsdDiscoveryDescriptor } from './apcupsd.discovery.js';
import { ApcupsdMapper } from './apcupsd.mapper.js';
import type { IApcupsdConfig } from './apcupsd.types.js';

export class ApcupsdIntegration extends BaseIntegration<IApcupsdConfig> {
  public readonly domain = 'apcupsd';
  public readonly displayName = 'APC UPS Daemon';
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createApcupsdDiscoveryDescriptor();
  public readonly configFlow = new ApcupsdConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/apcupsd',
    upstreamDomain: 'apcupsd',
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'platinum',
    requirements: ['aioapcaccess==1.0.0'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@yuxincs'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/apcupsd',
    discovery: {
      manual: true,
      note: 'Home Assistant APCUPSd has no automatic discovery; manual NIS host/port and snapshot inputs are implemented.',
    },
    runtime: {
      type: 'read-only-runtime',
      polling: 'local TCP APCUPSd NIS status command',
      services: ['snapshot', 'status', 'refresh'],
      controls: false,
    },
  };

  public async setup(configArg: IApcupsdConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new ApcupsdRuntime(new ApcupsdClient(configArg));
  }

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

export class HomeAssistantApcupsdIntegration extends ApcupsdIntegration {}

class ApcupsdRuntime implements IIntegrationRuntime {
  public domain = 'apcupsd';

  constructor(private readonly client: ApcupsdClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain !== 'apcupsd') {
        return { success: false, error: `Unsupported APCUPSd service domain: ${requestArg.domain}` };
      }
      if (requestArg.service === 'snapshot' || requestArg.service === 'status') {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.service === 'refresh') {
        return { success: true, data: await this.client.refresh() };
      }
      return { success: false, error: `Unsupported APCUPSd service: ${requestArg.service}` };
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

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