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 { PiHoleClient } from './pi_hole.classes.client.js';
import { PiHoleConfigFlow } from './pi_hole.classes.configflow.js';
import { createPiHoleDiscoveryDescriptor } from './pi_hole.discovery.js';
import { PiHoleMapper } from './pi_hole.mapper.js';
import type { IPiHoleConfig } from './pi_hole.types.js';
import { piHoleDomain } from './pi_hole.types.js';

export class PiHoleIntegration extends BaseIntegration<IPiHoleConfig> {
  public readonly domain = piHoleDomain;
  public readonly displayName = 'Pi-hole';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createPiHoleDiscoveryDescriptor();
  public readonly configFlow = new PiHoleConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/pi_hole',
    upstreamDomain: piHoleDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['hole==0.9.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@shenxn'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/pi_hole',
    protocolSource: 'Pi-hole HTTP APIs: v5 /admin/api.php summaryRaw/versions/enable/disable and v6 /api/auth, /api/stats/summary, /api/dns/blocking, /api/info/version.',
    runtime: {
      type: 'control-runtime',
      polling: 'local Pi-hole HTTP API',
      services: ['snapshot', 'status', 'refresh', 'enable', 'disable'],
      controls: ['dns_blocking'],
      liveCommandSuccessRequiresClientOrExecutor: true,
    },
    localApi: {
      implemented: [
        'Pi-hole API v6 authenticated summary, blocking status, version, enable, and disable endpoints',
        'Pi-hole API v5 summaryRaw, versions, enable, and disable endpoints',
        'manual raw API data and normalized snapshot inputs',
        'status, statistics, update, and DNS-blocking switch entity mappings',
      ],
      explicitUnsupported: [
        'Home Assistant Python hole compatibility wrapper',
        'fake live enable/disable success without a configured HTTP endpoint or command executor',
      ],
    },
  };

  public async setup(configArg: IPiHoleConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new PiHoleRuntime(new PiHoleClient(configArg));
  }

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

export class HomeAssistantPiHoleIntegration extends PiHoleIntegration {}

class PiHoleRuntime implements IIntegrationRuntime {
  public domain = piHoleDomain;

  constructor(private readonly client: PiHoleClient) {}

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

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

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

      const snapshot = await this.client.getSnapshot();
      const command = PiHoleMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported Pi-hole service mapping: ${requestArg.domain}.${requestArg.service}` };
      }
      if ('error' in command) {
        return { success: false, error: command.error };
      }
      return this.client.sendCommand(command);
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

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