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

import { Characteristic, Service, Categories } from '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`);
Category = Category.join('\n');

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

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