---
import Base from '../../layouts/Base.astro';
import fs from 'node:fs';
import path from 'node:path';

export function getStaticPaths() {
  const dataDir = path.join(process.cwd(), 'src/data/comics');
  if (!fs.existsSync(dataDir)) return [];
  const files = fs.readdirSync(dataDir).filter(f => f.endsWith('.html'));
  
  return files.map(file => {
    const slug = file.replace('.html', '');
    return {
      params: { slug },
      props: { filePath: path.join(dataDir, file) }
    };
  });
}

const { filePath } = Astro.props;
const html = fs.readFileSync(filePath, 'utf-8');

// Extract title
const titleMatch = html.match(/<title>([^<]+)<\/title>/i);
const title = titleMatch ? titleMatch[1].replace(/&amp;/g, '&').replace(/&#039;/g, "'") : 'Comics';

// Extract meta description
const descMatch = html.match(/<meta\s+name="description"\s+content="([^"]*)"/i);
const description = descMatch ? descMatch[1] : '';

// Extract body content
let content = html;
const bodyStart = content.indexOf('<body');
if (bodyStart > 0) {
  const bodyTagEnd = content.indexOf('>', bodyStart);
  content = content.substring(bodyTagEnd + 1);
}
const bodyEnd = content.indexOf('</body>');
if (bodyEnd > 0) {
  content = content.substring(0, bodyEnd);
}

// Try to extract d-content-wrap
const contentWrapStart = content.indexOf('class="d-content-wrap"');
if (contentWrapStart > 0) {
  const tagStart = content.lastIndexOf('<div', contentWrapStart);
  content = content.substring(tagStart);
  const footerStart = content.indexOf('<div class="d-footer">');
  if (footerStart > 0) content = content.substring(0, footerStart);
}

// Clean up old script references
content = content.replace(/<script[^>]*src="[^"]*dextronet[^"]*"[^>]*><\/script>/gi, '');
content = content.replace(/<script[^>]*src="[^"]*plugins[^"]*"[^>]*><\/script>/gi, '');
---
<Base title={title} description={description}>
  <Fragment set:html={content} />
</Base>
