---
import { createMarkdownProcessor } from '@astrojs/markdown-remark';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

interface Props {
  plugin: string;
}

const { plugin } = Astro.props;

async function importMDX(plugin: string): Promise<string> {
  const base = fileURLToPath(import.meta.url);
  const dirname = path.dirname(base);

  const mdPath = path.join(
    dirname,
    '../../packages/plugins-workspace/plugins',
    plugin,
    'permissions/autogenerated',
    'reference.md'
  );

  try {
    const content = await fs.readFile(mdPath, 'utf-8');
    return content;
  } catch (err) {
    console.error(`Error reading file ${mdPath}: ${err}`);
    throw err;
  }
}
const md = await createMarkdownProcessor();

const pageContent: string = await importMDX(plugin);
const content = await md.render(pageContent);
let code = content.code;

for (const heading of ['h1', 'h2', 'h3', 'h4']) {
  code = code.replace(
    new RegExp(`<${heading} id="([A-Za-z0-9\-]+)">([A-Za-z0-9\- ]+)</${heading}>`),
    `<${heading} id="$1"><a href="#$1" class="heading-link">$2</a></${heading}>`
  );
}
---

<Fragment set:html={code} />
