import fs from 'node:fs/promises';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { setupElegantRouter } from '../build/plugins/router.ts';

const currentFilePath = fileURLToPath(import.meta.url);
const currentDirPath = path.dirname(currentFilePath);
const rootDir = path.resolve(currentDirPath, '..');

const generatedFiles = [
  path.resolve(rootDir, 'src/router/elegant/imports.ts'),
  path.resolve(rootDir, 'src/router/elegant/routes.ts'),
  path.resolve(rootDir, 'src/router/elegant/transform.ts'),
  path.resolve(rootDir, 'src/typings/elegant-router.d.ts')
];

async function getMtimeMs(filePath) {
  try {
    const stat = await fs.stat(filePath);
    return stat.mtimeMs;
  } catch {
    return 0;
  }
}

async function getGeneratedFileMtimes() {
  return Promise.all(generatedFiles.map(getMtimeMs));
}

function isGenerated(before, after) {
  return after.some((mtimeMs, index) => mtimeMs !== before[index]);
}

async function waitForGeneration(beforeMtimes, timeoutMs = 10000) {
  const startTime = Date.now();

  async function poll() {
    const afterMtimes = await getGeneratedFileMtimes();

    if (isGenerated(beforeMtimes, afterMtimes)) {
      return;
    }

    if (Date.now() - startTime >= timeoutMs) {
      throw new Error('Timed out while waiting for elegant-router generated files.');
    }

    await new Promise(resolve => {
      setTimeout(resolve, 100);
    });

    await poll();
  }

  await poll();
}

process.chdir(rootDir);

const beforeMtimes = await getGeneratedFileMtimes();

setupElegantRouter();

await waitForGeneration(beforeMtimes);

console.log('Generated elegant-router files.');
