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 { HddtempClient } from './hddtemp.classes.client.js';
import { HddtempConfigFlow } from './hddtemp.classes.configflow.js';
import { createHddtempDiscoveryDescriptor } from './hddtemp.discovery.js';
import { HddtempMapper } from './hddtemp.mapper.js';
import type { IHddtempConfig } from './hddtemp.types.js';
import { hddtempDefaultPort, hddtempDisplayName, hddtempDomain } from './hddtemp.types.js';

export class HddtempIntegration extends BaseIntegration<IHddtempConfig> {
  public readonly domain = hddtempDomain;
  public readonly displayName = hddtempDisplayName;
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createHddtempDiscoveryDescriptor();
  public readonly configFlow = new HddtempConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/hddtemp',
    upstreamDomain: hddtempDomain,
    iotClass: 'local_polling',
    qualityScale: 'legacy',
    requirements: [] as string[],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: [] as string[],
    documentation: 'https://www.home-assistant.io/integrations/hddtemp',
    discovery: {
      manual: true,
      customTcp: true,
      defaultPort: hddtempDefaultPort,
      note: 'Home Assistant hddtemp has no automatic discovery; manual host/port, custom TCP candidates, injected clients, snapshots, and raw daemon output are implemented.',
    },
    runtime: {
      type: 'read-only-runtime',
      polling: 'local TCP hddtemp daemon snapshot',
      services: ['snapshot', 'status', 'refresh'],
      controls: false,
    },
    localApi: {
      implemented: [
        'manual hddtemp daemon host/port setup',
        'custom TCP candidate matching on port 7634 or daemon output',
        'ASCII daemon output parsing into disk temperature snapshots',
        'snapshot/raw-data/injected-client operation',
        'read-only device and sensor entity mapping',
      ],
      explicitUnsupported: [
        'write/control services; hddtemp is read-only',
        'claiming live success without a host, injected client, snapshot, or raw daemon data',
        'automatic LAN scans that probe arbitrary hosts',
      ],
    },
  };

  public async setup(configArg: IHddtempConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HddtempRuntime(new HddtempClient(configArg));
  }

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

export class HomeAssistantHddtempIntegration extends HddtempIntegration {}

class HddtempRuntime implements IIntegrationRuntime {
  public domain = hddtempDomain;

  constructor(private readonly client: HddtempClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain !== hddtempDomain) {
        return { success: false, error: `Unsupported hddtemp service domain: ${requestArg.domain}` };
      }
      if (requestArg.service === 'snapshot' || requestArg.service === 'status') {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.service === 'refresh') {
        const result = await this.client.refresh();
        return { success: result.success, error: result.error, data: result.snapshot || result.data };
      }
      return { success: false, error: `Unsupported hddtemp 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();
  }
}
