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 { DlnaDmsClient } from './dlna_dms.classes.client.js';
import { DlnaDmsConfigFlow } from './dlna_dms.classes.configflow.js';
import { createDlnaDmsDiscoveryDescriptor } from './dlna_dms.discovery.js';
import { DlnaDmsMapper } from './dlna_dms.mapper.js';
import type { IDlnaDmsConfig } from './dlna_dms.types.js';
import { dlnaDmsDomain } from './dlna_dms.types.js';

export class DlnaDmsIntegration extends BaseIntegration<IDlnaDmsConfig> {
  public readonly domain = dlnaDmsDomain;
  public readonly displayName = 'DLNA Digital Media Server';
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createDlnaDmsDiscoveryDescriptor();
  public readonly configFlow = new DlnaDmsConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/dlna_dms',
    upstreamDomain: dlnaDmsDomain,
    integrationType: 'service',
    iotClass: 'local_polling',
    requirements: ['async-upnp-client==0.46.2'],
    dependencies: ['ssdp'],
    afterDependencies: ['media_source'],
    codeowners: ['@chishm'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/dlna_dms',
    runtime: {
      type: 'read-only-runtime',
      polling: 'local UPnP ContentDirectory Browse and ConnectionManager SOAP requests',
      services: ['snapshot', 'status', 'refresh'],
      controls: false,
    },
    localApi: {
      implemented: [
        'SSDP and manual DLNA MediaServer candidates',
        'native UPnP device description parsing',
        'ContentDirectory root snapshot mapping for server, library, content directory, and status sensors',
        'read-only refresh service',
      ],
      explicitUnsupported: [
        'Home Assistant Python async_upnp_client compatibility layer',
        'media_source playback resolution/control services',
        'fake live UPnP success without a device description endpoint, snapshot, or injected client',
      ],
    },
  };

  public async setup(configArg: IDlnaDmsConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new DlnaDmsRuntime(new DlnaDmsClient(configArg));
  }

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

export class HomeAssistantDlnaDmsIntegration extends DlnaDmsIntegration {}

class DlnaDmsRuntime implements IIntegrationRuntime {
  public domain = dlnaDmsDomain;

  constructor(private readonly client: DlnaDmsClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain !== dlnaDmsDomain) {
        return { success: false, error: `Unsupported DLNA DMS 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 snapshot = await this.client.refresh();
        return snapshot.source !== 'runtime' || snapshot.online
          ? { success: true, data: snapshot }
          : { success: false, error: snapshot.error || 'DLNA DMS refresh requires a device description URL, snapshot, or client.', data: snapshot };
      }
      return { success: false, error: `Unsupported DLNA DMS 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();
  }
}
