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 { HuaweiLteClient } from './huawei_lte.classes.client.js';
import { HuaweiLteConfigFlow } from './huawei_lte.classes.configflow.js';
import { createHuaweiLteDiscoveryDescriptor } from './huawei_lte.discovery.js';
import { HuaweiLteMapper } from './huawei_lte.mapper.js';
import type { IHuaweiLteConfig } from './huawei_lte.types.js';
import { huaweiLteDefaultManufacturer, huaweiLteDisplayName, huaweiLteDomain, huaweiLteSsdpDeviceType, huaweiLteSsdpManufacturers } from './huawei_lte.types.js';

export class HuaweiLteIntegration extends BaseIntegration<IHuaweiLteConfig> {
  public readonly domain = huaweiLteDomain;
  public readonly displayName = huaweiLteDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createHuaweiLteDiscoveryDescriptor();
  public readonly configFlow = new HuaweiLteConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/huawei_lte',
    upstreamDomain: huaweiLteDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['huawei-lte-api==1.11.0', 'url-normalize==3.0.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@scop', '@fphammerle'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/huawei_lte',
    ssdp: huaweiLteSsdpManufacturers.map((manufacturerArg) => ({ deviceType: huaweiLteSsdpDeviceType, manufacturer: manufacturerArg })),
    defaults: {
      manufacturer: huaweiLteDefaultManufacturer,
      verifySsl: false,
      unauthenticatedMode: false,
      trackWiredClients: true,
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local Huawei HiLink HTTP/XML API endpoints under /api/*',
      services: ['snapshot', 'status', 'refresh', 'mobile data switch', 'guest WiFi switch', 'reboot', 'clear traffic statistics', 'send SMS', 'network mode select', 'suspend/resume integration'],
      controls: true,
    },
    localApi: {
      implemented: [
        'SSDP InternetGatewayDevice matching for Huawei, Huawei Technologies, and SOYEA manufacturers from the Home Assistant manifest',
        'manual URL/host/snapshot/raw-data/client setup',
        'local HiLink XML GET snapshots for device, signal, monitoring, traffic, net, SMS, LAN host, WLAN host, and WLAN settings endpoints',
        'local HiLink token handling and optional username/password login for POST writes',
        'real POST writes for dialup/mobile-dataswitch, wlan/multi-basic-settings guest network switch, device/control reboot, monitoring/clear-traffic, sms/send-sms, and net/net-mode',
        'injected client and commandExecutor operation for tests and alternate transports',
      ],
      explicitUnsupported: [
        'faking live command success for static snapshots or manual raw data',
        'encrypted profile/password-changing endpoints from huawei-lte-api',
        'full Home Assistant device_tracker platform parity because the shared runtime entity model has no device_tracker platform',
        'TLS certificate bypass through Node fetch; use HTTP, a valid certificate, or an injected client if the router uses a self-signed HTTPS certificate',
      ],
    },
  };

  public async setup(configArg: IHuaweiLteConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HuaweiLteRuntime(new HuaweiLteClient(configArg));
  }

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

export class HomeAssistantHuaweiLteIntegration extends HuaweiLteIntegration {}

class HuaweiLteRuntime implements IIntegrationRuntime {
  public domain = huaweiLteDomain;

  constructor(private readonly client: HuaweiLteClient) {}

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

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

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

      const snapshot = await this.client.getSnapshot();
      const command = HuaweiLteMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported Huawei LTE service: ${requestArg.domain}.${requestArg.service}` };
      }
      const data = await this.client.execute(command);
      return { success: true, data: data ?? command };
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

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