import { DiscoveryDescriptor } from '../../core/classes.discoverydescriptor.js';
import type { IDiscoveryCandidate, IDiscoveryMatch, IDiscoveryMatcher, IDiscoveryValidator } from '../../core/types.js';
import { BondMapper } from './bond.mapper.js';
import type { IBondDhcpRecord, IBondManualEntry, IBondRawData, IBondSnapshot, IBondZeroconfRecord } from './bond.types.js';
import { bondDefaultPort, bondDhcpHostnamePrefix, bondDhcpMacPrefixes, bondDisplayName, bondDomain, bondZeroconfType } from './bond.types.js';

export class BondZeroconfMatcher implements IDiscoveryMatcher<IBondZeroconfRecord> {
  public id = 'bond-zeroconf-match';
  public source = 'mdns' as const;
  public description = 'Recognize Bond _bond._tcp.local zeroconf advertisements from the Home Assistant manifest.';

  public async matches(recordArg: IBondZeroconfRecord): Promise<IDiscoveryMatch> {
    const txt = normalizeKeys({ ...recordArg.txt, ...recordArg.properties });
    const type = normalizeMdnsType(recordArg.type || recordArg.serviceType || '');
    const host = recordArg.host || recordArg.hostname || recordArg.addresses?.[0];
    const name = cleanServiceName(recordArg.name) || stringValue(txt.name) || bondDisplayName;
    const bondId = normalizeBondId(stringValue(txt.bondid) || stringValue(txt.id) || cleanServiceName(recordArg.name));
    const matched = type === normalizeMdnsType(bondZeroconfType) || type.includes('_bond') || recordArg.metadata?.bond === true;
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'mDNS record is not a Bond _bond advertisement.' };
    }
    return {
      matched: true,
      confidence: host && bondId ? 'certain' : host ? 'high' : 'medium',
      reason: 'mDNS service matches _bond._tcp.local.',
      normalizedDeviceId: bondId || recordArg.name || host,
      candidate: {
        source: 'mdns',
        integrationDomain: bondDomain,
        id: bondId || recordArg.name || host,
        host,
        port: recordArg.port || bondDefaultPort,
        name,
        manufacturer: 'Olibra',
        model: txt.model || txt.target || 'Bond Bridge',
        metadata: {
          ...recordArg.metadata,
          bond: true,
          discoveryProtocol: 'zeroconf',
          mdnsType: type,
          mdnsName: recordArg.name,
          txt,
        },
      },
    };
  }
}

export class BondDhcpMatcher implements IDiscoveryMatcher<IBondDhcpRecord> {
  public id = 'bond-dhcp-match';
  public source = 'dhcp' as const;
  public description = 'Recognize Bond DHCP leases with bond-* hostnames and 3C6A2C1/F44E38 MAC prefixes from the Home Assistant manifest.';

  public async matches(recordArg: IBondDhcpRecord): Promise<IDiscoveryMatch> {
    const hostname = stringValue(recordArg.hostname) || stringValue(recordArg.hostName) || '';
    const normalizedHostname = hostname.toLowerCase();
    const normalizedMac = normalizeMacPrefix(recordArg.macaddress || recordArg.macAddress);
    const hostMatches = normalizedHostname.startsWith(bondDhcpHostnamePrefix);
    const macMatches = Boolean(normalizedMac && bondDhcpMacPrefixes.some((prefixArg) => normalizedMac.startsWith(prefixArg)));
    const matched = (hostMatches && macMatches) || recordArg.metadata?.bond === true;
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'DHCP lease does not match Bond hostname and MAC prefixes.' };
    }
    const bondId = normalizeBondId(hostMatches ? hostname.slice(bondDhcpHostnamePrefix.length) : undefined);
    const host = recordArg.ip || recordArg.address;
    return {
      matched: true,
      confidence: host && bondId && macMatches ? 'certain' : host ? 'high' : 'medium',
      reason: 'DHCP lease matches Bond hostname and MAC prefixes.',
      normalizedDeviceId: bondId || normalizedMac || host,
      candidate: {
        source: 'dhcp',
        integrationDomain: bondDomain,
        id: bondId || normalizedMac || host,
        host,
        port: bondDefaultPort,
        name: bondId ? `Bond ${bondId}` : bondDisplayName,
        manufacturer: 'Olibra',
        macAddress: BondMapper.normalizeMac(normalizedMac),
        model: 'Bond Bridge',
        metadata: {
          ...recordArg.metadata,
          bond: true,
          discoveryProtocol: 'dhcp',
          hostname,
          macAddress: BondMapper.normalizeMac(normalizedMac),
        },
      },
    };
  }
}

export class BondManualMatcher implements IDiscoveryMatcher<IBondManualEntry> {
  public id = 'bond-manual-match';
  public source = 'manual' as const;
  public description = 'Recognize manual Bond host/token, snapshot, injected client, and raw-data setup entries.';

  public async matches(inputArg: IBondManualEntry): Promise<IDiscoveryMatch> {
    const metadata = inputArg.metadata || {};
    const parsed = parseEndpoint(inputArg.url || inputArg.host);
    const snapshot = snapshotValue(inputArg.snapshot || metadata.snapshot);
    const rawData = rawDataValue(inputArg.rawData || metadata.rawData);
    const hasManualData = Boolean(snapshot || rawData || inputArg.client || metadata.client);
    const text = [inputArg.name, inputArg.manufacturer, inputArg.model, metadata.name, metadata.manufacturer, metadata.model].filter(Boolean).join(' ').toLowerCase();
    const matched = Boolean(inputArg.host || inputArg.url || inputArg.accessToken || inputArg.token || metadata.bond || hasManualData || text.includes('bond'));
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'Manual entry does not contain Bond setup hints.' };
    }
    const host = parsed?.host || (inputArg.url ? undefined : inputArg.host) || snapshot?.hub.host;
    const port = inputArg.port || parsed?.port || snapshot?.hub.port || bondDefaultPort;
    const id = inputArg.id || inputArg.uniqueId || inputArg.bondId || snapshot?.hub.id || (host ? `${host}:${port}` : undefined);
    return {
      matched: true,
      confidence: host || hasManualData ? 'high' : 'medium',
      reason: 'Manual entry can start Bond setup.',
      normalizedDeviceId: id,
      candidate: {
        source: 'manual',
        integrationDomain: bondDomain,
        id,
        host,
        port,
        name: inputArg.name || snapshot?.hub.name || bondDisplayName,
        manufacturer: inputArg.manufacturer || snapshot?.hub.manufacturer || 'Olibra',
        model: inputArg.model || snapshot?.hub.model || snapshot?.hub.target,
        metadata: {
          ...metadata,
          bond: true,
          discoveryProtocol: 'manual',
          accessToken: inputArg.accessToken || inputArg.token || metadata.accessToken || metadata.token,
          snapshot,
          rawData,
          client: inputArg.client || metadata.client,
          commandExecutor: inputArg.commandExecutor || metadata.commandExecutor,
        },
      },
    };
  }
}

export class BondCandidateValidator implements IDiscoveryValidator {
  public id = 'bond-candidate-validator';
  public description = 'Validate Bond candidates from zeroconf, DHCP, and manual setup.';

  public async validate(candidateArg: IDiscoveryCandidate): Promise<IDiscoveryMatch> {
    const metadata = candidateArg.metadata || {};
    const snapshot = snapshotValue(metadata.snapshot);
    const rawData = rawDataValue(metadata.rawData);
    const mdnsType = typeof metadata.mdnsType === 'string' ? metadata.mdnsType.toLowerCase() : '';
    const discoveryProtocol = typeof metadata.discoveryProtocol === 'string' ? metadata.discoveryProtocol : undefined;
    const text = [candidateArg.integrationDomain, candidateArg.name, candidateArg.manufacturer, candidateArg.model, mdnsType].filter(Boolean).join(' ').toLowerCase();
    const matched = candidateArg.integrationDomain === bondDomain
      || metadata.bond === true
      || text.includes('bond')
      || mdnsType.includes('_bond')
      || discoveryProtocol === 'dhcp';
    const hasUsableSource = Boolean(candidateArg.host || snapshot || rawData || metadata.client);
    const normalizedDeviceId = candidateArg.id || snapshot?.hub.id || (candidateArg.host ? `${candidateArg.host}:${candidateArg.port || bondDefaultPort}` : undefined);
    if (!matched || !hasUsableSource) {
      return {
        matched: false,
        confidence: matched ? 'medium' : 'low',
        reason: matched ? 'Bond candidate lacks a host, injected client, snapshot, or manual raw data.' : 'Candidate is not Bond.',
        normalizedDeviceId,
      };
    }
    return {
      matched: true,
      confidence: candidateArg.host && normalizedDeviceId ? 'certain' : candidateArg.host ? 'high' : 'medium',
      reason: 'Candidate has Bond metadata and a usable local endpoint, client, snapshot, or manual raw data.',
      normalizedDeviceId,
      candidate: {
        ...candidateArg,
        integrationDomain: bondDomain,
        port: candidateArg.port || bondDefaultPort,
        manufacturer: candidateArg.manufacturer || 'Olibra',
      },
    };
  }
}

export const createBondDiscoveryDescriptor = (): DiscoveryDescriptor => {
  return new DiscoveryDescriptor({ integrationDomain: bondDomain, displayName: bondDisplayName })
    .addMatcher(new BondZeroconfMatcher())
    .addMatcher(new BondDhcpMatcher())
    .addMatcher(new BondManualMatcher())
    .addValidator(new BondCandidateValidator());
};

const normalizeMdnsType = (valueArg: string): string => valueArg.toLowerCase().replace(/\.$/, '');

const cleanServiceName = (valueArg: string | undefined): string | undefined => {
  if (!valueArg) {
    return undefined;
  }
  return valueArg.replace(/\._.*$/u, '').replace(/\.local\.?$/i, '').trim() || undefined;
};

const normalizeKeys = (recordArg: Record<string, string | undefined>): Record<string, string | undefined> => {
  const normalized: Record<string, string | undefined> = {};
  for (const [key, value] of Object.entries(recordArg)) {
    normalized[key.toLowerCase()] = value;
  }
  return normalized;
};

const normalizeBondId = (valueArg: string | undefined): string | undefined => valueArg?.replace(/^bond-/i, '').replace(/\..*$/, '').toUpperCase() || undefined;

const normalizeMacPrefix = (valueArg: unknown): string | undefined => typeof valueArg === 'string' ? valueArg.replace(/[^0-9a-f]/gi, '').toUpperCase() : undefined;

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

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 : `http://${valueArg}`);
    return { host: url.hostname, port: url.port ? Number(url.port) : undefined };
  } catch {
    return undefined;
  }
};

const snapshotValue = (valueArg: unknown): IBondSnapshot | undefined => valueArg && typeof valueArg === 'object' && 'hub' in valueArg && 'devices' in valueArg ? valueArg as IBondSnapshot : undefined;

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