import { writeFileSync } from 'node:fs';
import { resolve } from 'node:path';

import { Characteristic, Service, Categories } from '@homebridge/hap-nodejs';

/** Generate Service Types */

let Services = [
  'export const Services = {',
] as any;

const uuidMap = new Map();

for (const [name, value] of Object.entries(Service)) {
  if (value.UUID) {
    if (!uuidMap.has(value.UUID)) {
      // If the UUID does not exist, add a new entry
      Services.push(`    '${value.UUID}': '${name}',`);
      uuidMap.set(value.UUID, Services.length - 1);
    }
    Services.push(`    '${name}': '${value.UUID}',`);
  }
}

Services.push(`};\n\n`);
Services = Services.join('\n');

/** Generate Characteristic Types */

let Characteristics = [
  'export const Characteristics = {',
] as any;

for (const [name, value] of Object.entries(Characteristic)) {
  if (value.UUID) {
    Characteristics.push(`    '${value.UUID}': '${name}',`);
    Characteristics.push(`    '${name}': '${value.UUID}',`);
  }
}

Characteristics.push(`};\n\n`);
Characteristics = Characteristics.join('\n');

/** Generate Category Types */

let Category = [
  'export const Categories = {',
] as any;

// @ts-ignore
for (const [name, value] of Object.entries(Categories)) {
  if (typeof value === 'number') {
    Category.push(`    '${name}': ${value},`);
  }
}

Category.push(`};\n\n`);
Category = Category.join('\n');

let Enums = [
  'export const Enums = {',
] as any;

for (const [name, value] of Object.entries(Characteristic)) {
  if (typeof value === 'function' && value.prototype) {
    const staticKeys = Object.getOwnPropertyNames(value)
      .filter(
        key =>
          key !== 'length' &&
          key !== 'name' &&
          key !== 'prototype' &&
          key !== 'UUID' &&
          typeof (value as any)[key] !== 'function'
      );
    if (staticKeys.length > 0) {
      Enums.push(`  ${name}: {`);
      staticKeys.forEach(k => {
        Enums.push(`    ${(value as any)[k]}: '${k}',`);
      });
      Enums.push('  },');
    }
  }
}
Enums.push(`};\n`);
Enums = Enums.join('\n');

const out = `/* This file is automatically generated */\n\n` + Services + Characteristics + Category + Enums

writeFileSync(resolve(__dirname, '../src/hap-types.ts'), out, 'utf8');
