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 { AdguardClient } from './adguard.classes.client.js';
import { AdguardConfigFlow } from './adguard.classes.configflow.js';
import { createAdguardDiscoveryDescriptor } from './adguard.discovery.js';
import { AdguardMapper } from './adguard.mapper.js';
import type { IAdguardConfig } from './adguard.types.js';

export class AdguardIntegration extends BaseIntegration<IAdguardConfig> {
  public readonly domain = 'adguard';
  public readonly displayName = 'AdGuard Home';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createAdguardDiscoveryDescriptor();
  public readonly configFlow = new AdguardConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/adguard',
    upstreamDomain: 'adguard',
    integrationType: 'service',
    iotClass: 'local_polling',
    requirements: ['adguardhome==0.8.1'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@frenck'],
    documentation: 'https://www.home-assistant.io/integrations/adguard',
    protocolSource: 'AdGuard Home HTTP API under /control: status, filtering, querylog, safebrowsing, safesearch, parental, stats, version, and update endpoints.',
    runtime: {
      type: 'control-runtime',
      polling: 'local HTTP AdGuard Home API',
      services: ['snapshot', 'status', 'add_url', 'remove_url', 'enable_url', 'disable_url', 'refresh'],
      controls: ['protection', 'filtering', 'querylog', 'safebrowsing', 'safesearch', 'parental'],
      liveCommandSuccessRequiresClientOrExecutor: true,
    },
  };

  public async setup(configArg: IAdguardConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new AdguardRuntime(new AdguardClient(configArg));
  }

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

export class HomeAssistantAdguardIntegration extends AdguardIntegration {}

class AdguardRuntime implements IIntegrationRuntime {
  public domain = 'adguard';

  constructor(private readonly client: AdguardClient) {}

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

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

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

      const snapshot = await this.client.getSnapshot();
      const command = AdguardMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported AdGuard Home 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();
  }
}
