import { DiscoveryDescriptor } from '../../core/classes.discoverydescriptor.js';
import type { IDiscoveryCandidate, IDiscoveryContext, IDiscoveryMatch, IDiscoveryMatcher, IDiscoveryValidator } from '../../core/types.js';
import { GoodweMapper } from './goodwe.mapper.js';
import type { IGoodweManualEntry, IGoodweRawData, IGoodweSnapshot } from './goodwe.types.js';
import { goodweDefaultUdpPort, goodweDisplayName, goodweDomain, goodweManufacturer } from './goodwe.types.js';

export class GoodweManualMatcher implements IDiscoveryMatcher<IGoodweManualEntry> {
  public id = 'goodwe-manual-match';
  public source = 'manual' as const;
  public description = 'Recognize manual GoodWe host, snapshot, raw-data, injected-client, and command-executor setup entries.';

  public async matches(inputArg: IGoodweManualEntry, contextArg: IDiscoveryContext): Promise<IDiscoveryMatch> {
    void contextArg;
    const metadata = inputArg.metadata || {};
    const parsed = parseEndpoint(inputArg.host);
    const snapshot = snapshotValue(inputArg.snapshot || metadata.snapshot);
    const rawData = rawDataValue(inputArg.rawData || metadata.rawData || rawDataFromInput(inputArg));
    const hasManualData = Boolean(snapshot || rawData || inputArg.client || metadata.client);
    const text = [inputArg.name, inputArg.manufacturer, inputArg.model, inputArg.modelFamily, metadata.name, metadata.manufacturer, metadata.model, metadata.modelFamily].filter(Boolean).join(' ').toLowerCase();
    const matched = Boolean(inputArg.host || inputArg.serialNumber || inputArg.modelFamily || metadata.goodwe || hasManualData || text.includes('goodwe') || text.includes('good we'));
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'Manual entry does not contain GoodWe setup hints.' };
    }

    const host = parsed?.host || inputArg.host || snapshot?.inverter.host || stringValue(metadata.host);
    const port = inputArg.port || parsed?.port || snapshot?.inverter.port || numberValue(metadata.port) || goodweDefaultUdpPort;
    const id = inputArg.id || inputArg.uniqueId || inputArg.serialNumber || snapshot?.inverter.serialNumber || snapshot?.inverter.id || (host ? `${host}:${port}` : undefined);
    return {
      matched: true,
      confidence: host || hasManualData ? 'high' : 'medium',
      reason: 'Manual entry can start GoodWe setup.',
      normalizedDeviceId: id,
      candidate: {
        source: 'manual',
        integrationDomain: goodweDomain,
        id,
        host,
        port,
        name: inputArg.name || snapshot?.inverter.name || goodweDisplayName,
        manufacturer: inputArg.manufacturer || snapshot?.inverter.manufacturer || goodweManufacturer,
        model: inputArg.model || snapshot?.inverter.model,
        serialNumber: inputArg.serialNumber || snapshot?.inverter.serialNumber,
        metadata: {
          ...metadata,
          goodwe: true,
          discoveryProtocol: 'manual',
          modelFamily: inputArg.modelFamily || snapshot?.inverter.modelFamily || metadata.modelFamily,
          snapshot,
          rawData,
          client: inputArg.client || metadata.client,
          commandExecutor: inputArg.commandExecutor || metadata.commandExecutor,
        },
      },
    };
  }
}

export class GoodweCandidateValidator implements IDiscoveryValidator {
  public id = 'goodwe-candidate-validator';
  public description = 'Validate GoodWe candidates from manual setup and externally supplied discovery data.';

  public async validate(candidateArg: IDiscoveryCandidate, contextArg: IDiscoveryContext): Promise<IDiscoveryMatch> {
    void contextArg;
    const metadata = candidateArg.metadata || {};
    const snapshot = snapshotValue(metadata.snapshot);
    const rawData = rawDataValue(metadata.rawData);
    const text = [candidateArg.integrationDomain, candidateArg.name, candidateArg.manufacturer, candidateArg.model, metadata.name, metadata.manufacturer, metadata.model, metadata.modelFamily].filter(Boolean).join(' ').toLowerCase();
    const matched = candidateArg.integrationDomain === goodweDomain
      || metadata.goodwe === true
      || text.includes('goodwe')
      || text.includes('good we');
    const hasUsableSource = Boolean(candidateArg.host || snapshot || rawData || metadata.client);
    const normalizedDeviceId = candidateArg.serialNumber || candidateArg.id || snapshot?.inverter.serialNumber || snapshot?.inverter.id || (candidateArg.host ? `${candidateArg.host}:${candidateArg.port || goodweDefaultUdpPort}` : undefined);
    if (!matched || !hasUsableSource) {
      return {
        matched: false,
        confidence: matched ? 'medium' : 'low',
        reason: matched ? 'GoodWe candidate lacks a host, injected client, snapshot, or raw data.' : 'Candidate is not GoodWe.',
        normalizedDeviceId,
      };
    }
    return {
      matched: true,
      confidence: candidateArg.host && normalizedDeviceId ? 'certain' : candidateArg.host ? 'high' : 'medium',
      reason: 'Candidate has GoodWe metadata and a local host, injected client, snapshot, or raw data.',
      normalizedDeviceId,
      candidate: {
        ...candidateArg,
        integrationDomain: goodweDomain,
        port: candidateArg.port || goodweDefaultUdpPort,
        manufacturer: candidateArg.manufacturer || goodweManufacturer,
      },
    };
  }
}

export const createGoodweDiscoveryDescriptor = (): DiscoveryDescriptor => {
  return new DiscoveryDescriptor({ integrationDomain: goodweDomain, displayName: goodweDisplayName })
    .addMatcher(new GoodweManualMatcher())
    .addValidator(new GoodweCandidateValidator());
};

const parseEndpoint = (valueArg: string | undefined): { host: string; port?: number } | undefined => {
  if (!valueArg) {
    return undefined;
  }
  try {
    const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(valueArg) ? valueArg : `goodwe://${valueArg}`);
    return { host: url.hostname, port: url.port ? Number(url.port) : undefined };
  } catch {
    return undefined;
  }
};

const rawDataFromInput = (inputArg: IGoodweManualEntry): Partial<IGoodweRawData> | undefined => {
  const rawData: Partial<IGoodweRawData> = {
    deviceInfo: GoodweMapper.cleanObject({
      host: inputArg.host,
      port: inputArg.port,
      name: inputArg.name,
      manufacturer: inputArg.manufacturer,
      model: inputArg.model,
      modelFamily: inputArg.modelFamily,
      serialNumber: inputArg.serialNumber,
      firmware: inputArg.firmware,
      armFirmware: inputArg.armFirmware,
      ratedPower: inputArg.ratedPower,
    }),
    runtimeData: inputArg.runtimeData,
    settingsData: inputArg.settingsData,
    sensors: inputArg.sensors,
    settings: inputArg.settings,
  };
  return Object.values(rawData).some(Boolean) ? rawData : undefined;
};

const snapshotValue = (valueArg: unknown): IGoodweSnapshot | undefined => {
  return valueArg && typeof valueArg === 'object' && 'inverter' in valueArg && 'runtimeData' in valueArg ? valueArg as IGoodweSnapshot : undefined;
};

const rawDataValue = (valueArg: unknown): Partial<IGoodweRawData> | undefined => {
  return valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg) ? valueArg as Partial<IGoodweRawData> : undefined;
};

const stringValue = (valueArg: unknown): string | undefined => typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;

const numberValue = (valueArg: unknown): number | undefined => {
  if (typeof valueArg === 'number' && Number.isFinite(valueArg)) {
    return valueArg;
  }
  if (typeof valueArg === 'string' && valueArg.trim()) {
    const parsed = Number(valueArg);
    return Number.isFinite(parsed) ? parsed : undefined;
  }
  return undefined;
};
