// build-config-file.ts
import * as fs from 'fs';
import * as path from 'path';
import { loadEnv } from 'vite';
import chokidar from 'chokidar';
import * as prettier from 'prettier';

// Get CLI args
const modeIndex = process.argv.indexOf('--mode');
const mode = modeIndex !== -1 ? process.argv[modeIndex + 1] : 'development';
const isWatch = process.argv.includes('--watch');

const OUTPUT_PATH = path.resolve(process.cwd(), 'public/config.js');

async function buildConfig() {
  const env = loadEnv(mode, process.cwd(), 'VITE_');

  const config = {
    COMPANY_NAME: env.VITE_APP_COMPANY_NAME,
    IWS5_API_URL: env.VITE_API_URL,
    ENABLE_RWP_COMPANION: env.VITE_ENABLE_RWP_COMPANION,
    ENABLE_LPNU_WORK_ITEM_SIGNAGE: env.VITE_ENABLE_LPNU_WORK_ITEM_SIGNAGE,
    LPNU_WORK_ITEM_SIGNAGE_CERTIFICATE_ISSUERS:
      String(env.VITE_ENABLE_LPNU_WORK_ITEM_SIGNAGE).toLowerCase() === 'true'
        ? async () => {
            try {
              const response = await fetch(
                'https://cabinet.tax.gov.ua/ws/api/crypto/public_sign/data/CAs.json'
              );
              const json = await response.json();
              return json.map((item) => String(item['issuerCNs'][0]));
            } catch {
              return [];
            }
          }
        : async () => {
            return [];
          },
  };

  // Custom serializer that preserves functions
  const serializeObject = (obj: Record<string, any>, indent = 2) => {
    const entries = Object.entries(obj)
      .map(([key, value]) => {
        const serialized =
          typeof value === 'function'
            ? value.toString()
            : JSON.stringify(value);
        return `${' '.repeat(indent)}"${key}": ${serialized}`;
      })
      .join(',\n');

    return `{\n${entries}\n${' '.repeat(indent - 2)}}`;
  };

  const content =
    `// Auto-generated from .env.${mode}\n` +
    `window.__APP_CONFIG__ = ${serializeObject(config)};\n`;

  const output = await prettier.format(content, {
    parser: 'babel',
    quoteProps: 'preserve',
  });

  fs.writeFileSync(OUTPUT_PATH, output);
  console.log(`[build-config-file] Updated config.js (using .env.${mode})`);
}

buildConfig();

if (isWatch) {
  const filesToWatch = [
    path.resolve(process.cwd(), '.env'),
    path.resolve(process.cwd(), `.env.${mode}`),
  ];

  console.log(
    `[build-config-file] Watching for changes in: ${filesToWatch.join(', ')}`
  );

  chokidar.watch(filesToWatch, { ignoreInitial: true }).on('change', () => {
    buildConfig();
  });
}
