import { DiscoveryDescriptor } from '../../core/classes.discoverydescriptor.js';
import type { IDiscoveryCandidate, IDiscoveryMatch, IDiscoveryMatcher, IDiscoveryValidator } from '../../core/types.js';
import type { IKodiManualEntry, IKodiMdnsRecord } from './kodi.types.js';

const defaultPort = 8080;
const defaultWsPort = 9090;
const kodiMdnsType = '_xbmc-jsonrpc-h._tcp.local';

export class KodiMdnsMatcher implements IDiscoveryMatcher<IKodiMdnsRecord> {
  public id = 'kodi-mdns-match';
  public source = 'mdns' as const;
  public description = 'Recognize Kodi JSON-RPC mDNS advertisements.';

  public async matches(recordArg: IKodiMdnsRecord): Promise<IDiscoveryMatch> {
    const type = normalizeType(recordArg.type);
    const properties = { ...recordArg.txt, ...recordArg.properties };
    const uuid = valueForKey(properties, 'uuid') || valueForKey(properties, 'id');
    const name = cleanName(valueForKey(properties, 'name') || recordArg.name || recordArg.hostname);
    const matched = type === kodiMdnsType || Boolean(uuid && type.includes('xbmc-jsonrpc')) || Boolean(name?.toLowerCase().includes('kodi'));
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'mDNS record is not a Kodi JSON-RPC advertisement.' };
    }
    return {
      matched: true,
      confidence: uuid ? 'certain' : 'high',
      reason: 'mDNS record matches Kodi JSON-RPC metadata.',
      normalizedDeviceId: uuid,
      candidate: {
        source: 'mdns',
        integrationDomain: 'kodi',
        id: uuid,
        host: recordArg.host || recordArg.addresses?.[0],
        port: recordArg.port || defaultPort,
        name,
        manufacturer: 'Kodi',
        model: valueForKey(properties, 'version') ? 'Kodi Media Center' : undefined,
        metadata: {
          mdnsName: recordArg.name,
          mdnsType: recordArg.type,
          txt: properties,
          wsPort: defaultWsPort,
        },
      },
    };
  }
}

export class KodiManualMatcher implements IDiscoveryMatcher<IKodiManualEntry> {
  public id = 'kodi-manual-match';
  public source = 'manual' as const;
  public description = 'Recognize manual Kodi setup entries.';

  public async matches(inputArg: IKodiManualEntry): Promise<IDiscoveryMatch> {
    const haystack = `${inputArg.name || ''} ${inputArg.model || ''} ${inputArg.manufacturer || ''}`.toLowerCase();
    const matched = Boolean(inputArg.host || inputArg.metadata?.kodi || haystack.includes('kodi') || haystack.includes('xbmc'));
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'Manual entry does not contain Kodi setup hints.' };
    }
    const id = inputArg.uuid || inputArg.id;
    return {
      matched: true,
      confidence: inputArg.host ? 'high' : 'medium',
      reason: 'Manual entry can start Kodi setup.',
      normalizedDeviceId: id,
      candidate: {
        source: 'manual',
        integrationDomain: 'kodi',
        id,
        host: inputArg.host,
        port: inputArg.port || defaultPort,
        name: inputArg.name,
        manufacturer: inputArg.manufacturer || 'Kodi',
        model: inputArg.model,
        metadata: {
          ...inputArg.metadata,
          wsPort: inputArg.wsPort || defaultWsPort,
          ssl: inputArg.ssl,
        },
      },
    };
  }
}

export class KodiCandidateValidator implements IDiscoveryValidator {
  public id = 'kodi-candidate-validator';
  public description = 'Validate Kodi candidate metadata.';

  public async validate(candidateArg: IDiscoveryCandidate): Promise<IDiscoveryMatch> {
    const manufacturer = candidateArg.manufacturer?.toLowerCase() || '';
    const model = candidateArg.model?.toLowerCase() || '';
    const name = candidateArg.name?.toLowerCase() || '';
    const matched = candidateArg.integrationDomain === 'kodi'
      || manufacturer.includes('kodi')
      || manufacturer.includes('xbmc')
      || model.includes('kodi')
      || model.includes('xbmc')
      || name.includes('kodi')
      || Boolean(candidateArg.metadata?.kodi);
    return {
      matched,
      confidence: matched && candidateArg.host ? 'high' : matched ? 'medium' : 'low',
      reason: matched ? 'Candidate has Kodi metadata.' : 'Candidate is not Kodi.',
      candidate: matched ? candidateArg : undefined,
      normalizedDeviceId: candidateArg.id,
    };
  }
}

export const createKodiDiscoveryDescriptor = (): DiscoveryDescriptor => {
  return new DiscoveryDescriptor({ integrationDomain: 'kodi', displayName: 'Kodi' })
    .addMatcher(new KodiMdnsMatcher())
    .addMatcher(new KodiManualMatcher())
    .addValidator(new KodiCandidateValidator());
};

const normalizeType = (valueArg?: string): string => {
  return (valueArg || '').toLowerCase().replace(/\.$/, '');
};

const valueForKey = (recordArg: Record<string, string | undefined> | undefined, keyArg: string): string | undefined => {
  if (!recordArg) {
    return undefined;
  }
  const lowerKey = keyArg.toLowerCase();
  for (const [key, value] of Object.entries(recordArg)) {
    if (key.toLowerCase() === lowerKey) {
      return value;
    }
  }
  return undefined;
};

const cleanName = (valueArg: string | undefined): string | undefined => {
  return valueArg?.replace(/\._xbmc-jsonrpc-h\._tcp\.local\.?$/i, '').replace(/\.local\.?$/i, '').trim() || undefined;
};
