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 { IppClient } from './ipp.classes.client.js';
import { IppConfigFlow } from './ipp.classes.configflow.js';
import { createIppDiscoveryDescriptor } from './ipp.discovery.js';
import { IppMapper } from './ipp.mapper.js';
import type { IIppConfig } from './ipp.types.js';

export class IppIntegration extends BaseIntegration<IIppConfig> {
  public readonly domain = 'ipp';
  public readonly displayName = 'Internet Printing Protocol (IPP)';
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createIppDiscoveryDescriptor();
  public readonly configFlow = new IppConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/ipp',
    upstreamDomain: 'ipp',
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['pyipp==0.17.0'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@ctalkington'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/ipp',
    zeroconf: ['_ipps._tcp.local.', '_ipp._tcp.local.'],
    runtime: {
      type: 'read-only-runtime',
      polling: 'local HTTP(S) IPP Get-Printer-Attributes request',
      services: ['snapshot', 'status', 'refresh'],
      controls: false,
    },
  };

  public async setup(configArg: IIppConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new IppRuntime(new IppClient(configArg));
  }

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

export class HomeAssistantIppIntegration extends IppIntegration {}

class IppRuntime implements IIntegrationRuntime {
  public domain = 'ipp';

  constructor(private readonly client: IppClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain !== 'ipp') {
        return { success: false, error: `Unsupported IPP service domain: ${requestArg.domain}` };
      }
      if (requestArg.service === 'snapshot' || requestArg.service === 'status') {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.service === 'refresh') {
        const snapshot = await this.client.refresh();
        return snapshot.source !== 'runtime' || snapshot.online
          ? { success: true, data: snapshot }
          : { success: false, error: snapshot.error || 'IPP refresh requires a host, snapshot, attributes, or client.', data: snapshot };
      }
      return { success: false, error: `Unsupported IPP 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();
  }
}
