import { DiscoveryDescriptor } from '../../core/classes.discoverydescriptor.js';
import type { IDiscoveryCandidate, IDiscoveryMatch, IDiscoveryMatcher, IDiscoveryValidator } from '../../core/types.js';
import type { IGlancesHttpCandidateRecord, IGlancesManualEntry, IGlancesSnapshot } from './glances.types.js';
import { glancesDefaultPort, glancesDomain } from './glances.types.js';

export class GlancesManualMatcher implements IDiscoveryMatcher<IGlancesManualEntry> {
  public id = 'glances-manual-match';
  public source = 'manual' as const;
  public description = 'Recognize manual Glances local HTTP and snapshot setup entries.';

  public async matches(inputArg: IGlancesManualEntry): Promise<IDiscoveryMatch> {
    const parsedUrl = parseUrl(inputArg.url);
    const metadata = inputArg.metadata || {};
    const hasManualData = Boolean(inputArg.snapshot || inputArg.rawData || inputArg.allData || inputArg.haSensorData || inputArg.sensorData || metadata.snapshot || metadata.rawData || metadata.haSensorData || metadata.sensorData);
    const text = [inputArg.name, inputArg.manufacturer, inputArg.model].filter(Boolean).join(' ').toLowerCase();
    const matched = Boolean(inputArg.host || parsedUrl || inputArg.port === glancesDefaultPort || metadata.glances || hasManualData || text.includes('glances') || text.includes('system monitor'));
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'Manual entry does not contain Glances setup hints.' };
    }

    const host = inputArg.host || parsedUrl?.host;
    const ssl = inputArg.ssl ?? parsedUrl?.ssl ?? booleanMetadata(metadata.ssl) ?? false;
    const port = inputArg.port || parsedUrl?.port || glancesDefaultPort;
    const id = inputArg.id || this.snapshotId(inputArg.snapshot || metadata.snapshot) || (host ? `${host}:${port}` : undefined);
    return {
      matched: true,
      confidence: host || hasManualData ? 'high' : 'medium',
      reason: 'Manual entry can start Glances setup.',
      normalizedDeviceId: id,
      candidate: {
        source: 'manual',
        integrationDomain: glancesDomain,
        id,
        host,
        port,
        name: inputArg.name,
        manufacturer: inputArg.manufacturer || 'Glances',
        model: inputArg.model || 'System Monitor',
        metadata: {
          ...metadata,
          glances: true,
          ssl,
          verifySsl: inputArg.verifySsl ?? metadata.verifySsl,
          username: inputArg.username ?? metadata.username,
          password: inputArg.password ?? metadata.password,
          apiVersion: inputArg.apiVersion || inputArg.version || metadata.apiVersion || parsedUrl?.apiVersion,
          url: inputArg.url,
          hasManualData,
          snapshot: inputArg.snapshot || metadata.snapshot,
          rawData: inputArg.rawData || inputArg.allData || metadata.rawData || metadata.allData,
          haSensorData: inputArg.haSensorData || inputArg.sensorData || metadata.haSensorData || metadata.sensorData,
        },
      },
    };
  }

  private snapshotId(valueArg: unknown): string | undefined {
    const snapshot = isGlancesSnapshot(valueArg) ? valueArg : undefined;
    return snapshot?.host.id || snapshot?.host.hostname || snapshot?.host.host;
  }
}

export class GlancesHttpMatcher implements IDiscoveryMatcher<IGlancesHttpCandidateRecord> {
  public id = 'glances-http-match';
  public source = 'http' as const;
  public description = 'Recognize local HTTP candidates that point at a Glances REST API.';

  public async matches(recordArg: IGlancesHttpCandidateRecord): Promise<IDiscoveryMatch> {
    const url = recordArg.url || recordArg.location;
    const parsedUrl = parseUrl(url);
    const headers = normalizeKeys(recordArg.headers || {});
    const metadata = recordArg.metadata || {};
    const text = [url, recordArg.name, recordArg.manufacturer, recordArg.model, headers.server, headers['x-powered-by']].filter(Boolean).join(' ').toLowerCase();
    const matched = Boolean(parsedUrl?.apiVersion || parsedUrl?.port === glancesDefaultPort || recordArg.port === glancesDefaultPort || metadata.glances || text.includes('glances'));
    if (!matched) {
      return { matched: false, confidence: 'low', reason: 'HTTP candidate does not look like a Glances API.' };
    }
    const host = recordArg.host || parsedUrl?.host;
    const ssl = recordArg.ssl ?? parsedUrl?.ssl ?? false;
    const port = recordArg.port || parsedUrl?.port || glancesDefaultPort;
    const id = host ? `${host}:${port}` : undefined;
    return {
      matched: true,
      confidence: parsedUrl?.apiVersion && host ? 'high' : host ? 'medium' : 'low',
      reason: 'HTTP candidate has Glances API hints.',
      normalizedDeviceId: id,
      candidate: {
        source: 'http',
        integrationDomain: glancesDomain,
        id,
        host,
        port,
        name: recordArg.name || 'Glances',
        manufacturer: recordArg.manufacturer || 'Glances',
        model: recordArg.model || 'System Monitor',
        metadata: {
          ...metadata,
          glances: true,
          ssl,
          url,
          apiVersion: parsedUrl?.apiVersion,
          headers,
        },
      },
    };
  }
}

export class GlancesCandidateValidator implements IDiscoveryValidator {
  public id = 'glances-candidate-validator';
  public description = 'Validate Glances candidates have a usable HTTP endpoint or snapshot/manual data.';

  public async validate(candidateArg: IDiscoveryCandidate): Promise<IDiscoveryMatch> {
    const metadata = candidateArg.metadata || {};
    const text = [candidateArg.integrationDomain, candidateArg.name, candidateArg.manufacturer, candidateArg.model].filter(Boolean).join(' ').toLowerCase();
    const matched = candidateArg.integrationDomain === glancesDomain
      || Boolean(metadata.glances)
      || candidateArg.port === glancesDefaultPort
      || text.includes('glances')
      || text.includes('system monitor');
    const hasManualData = Boolean(metadata.snapshot || metadata.rawData || metadata.allData || metadata.haSensorData || metadata.sensorData);
    const port = candidateArg.port || glancesDefaultPort;
    const hasUsableAddress = Boolean(candidateArg.host && isValidPort(port));

    if (!matched || (!hasUsableAddress && !hasManualData)) {
      return {
        matched: false,
        confidence: matched ? 'medium' : 'low',
        reason: matched ? 'Glances candidate lacks a usable host or snapshot/manual data.' : 'Candidate is not Glances.',
        normalizedDeviceId: candidateArg.id || (candidateArg.host ? `${candidateArg.host}:${port}` : undefined),
      };
    }

    const normalizedDeviceId = candidateArg.id || snapshotId(metadata.snapshot) || (candidateArg.host ? `${candidateArg.host}:${port}` : undefined);
    return {
      matched: true,
      confidence: normalizedDeviceId && hasUsableAddress ? 'certain' : hasUsableAddress ? 'high' : 'medium',
      reason: 'Candidate has Glances metadata and a usable HTTP endpoint or snapshot/manual data.',
      normalizedDeviceId,
      candidate: {
        ...candidateArg,
        integrationDomain: glancesDomain,
        port,
        manufacturer: candidateArg.manufacturer || 'Glances',
        model: candidateArg.model || 'System Monitor',
      },
    };
  }
}

export const createGlancesDiscoveryDescriptor = (): DiscoveryDescriptor => {
  return new DiscoveryDescriptor({ integrationDomain: glancesDomain, displayName: 'Glances' })
    .addMatcher(new GlancesManualMatcher())
    .addMatcher(new GlancesHttpMatcher())
    .addValidator(new GlancesCandidateValidator());
};

const parseUrl = (valueArg: string | undefined): { host: string; port?: number; ssl: boolean; apiVersion?: 3 | 4 } | undefined => {
  if (!valueArg) {
    return undefined;
  }
  try {
    const url = new URL(valueArg);
    const versionMatch = url.pathname.match(/\/api\/(3|4)(?:\/|$)/);
    return {
      host: url.hostname,
      port: url.port ? Number(url.port) : undefined,
      ssl: url.protocol === 'https:',
      apiVersion: versionMatch ? Number(versionMatch[1]) as 3 | 4 : undefined,
    };
  } catch {
    return 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 booleanMetadata = (valueArg: unknown): boolean | undefined => typeof valueArg === 'boolean' ? valueArg : undefined;

const isValidPort = (valueArg: number): boolean => Number.isInteger(valueArg) && valueArg > 0 && valueArg <= 65535;

const isGlancesSnapshot = (valueArg: unknown): valueArg is IGlancesSnapshot => Boolean(valueArg && typeof valueArg === 'object' && 'host' in valueArg && 'sensorData' in valueArg);

const snapshotId = (valueArg: unknown): string | undefined => {
  const snapshot = isGlancesSnapshot(valueArg) ? valueArg : undefined;
  return snapshot?.host.id || snapshot?.host.hostname || snapshot?.host.host;
};
