import { NextResponse } from 'next/server';
import fs from 'fs';

import zlib from 'zlib';

export async function GET() {
  try {
    const bundlePath = 'c:\\Users\\ASSIMILATE\\Downloads\\Meticulous Research Repositioning\\uploads\\files (1)\\Meticulous Protein Bar Report.html';
    if (!fs.existsSync(bundlePath)) {
      return new NextResponse('Bundle file not found', { status: 404 });
    }
    
    const content = fs.readFileSync(bundlePath, 'utf8');

    // Find the manifest script block
    const manifestStartTag = '<script type="__bundler/manifest">';
    const manifestStartIndex = content.indexOf(manifestStartTag);
    if (manifestStartIndex === -1) {
      return new NextResponse('Manifest not found', { status: 500 });
    }
    const manifestDataStart = manifestStartIndex + manifestStartTag.length;
    const manifestEndIndex = content.indexOf('</script>', manifestDataStart);
    const manifestJson = content.slice(manifestDataStart, manifestEndIndex);
    const manifest = JSON.parse(manifestJson);

    // Find the template script block
    const templateStartTag = '<script type="__bundler/template">';
    const templateStartIndex = content.indexOf(templateStartTag);
    if (templateStartIndex === -1) {
      return new NextResponse('Template not found', { status: 500 });
    }
    const templateDataStart = templateStartIndex + templateStartTag.length;
    const templateEndIndex = content.indexOf('</script>', templateDataStart);
    let template = JSON.parse(content.slice(templateDataStart, templateEndIndex));

    // Decode assets
    const uuids = Object.keys(manifest);
    const decodedAssets: Record<string, string> = {};
    for (const uuid of uuids) {
      const entry = manifest[uuid];
      const buffer = Buffer.from(entry.data, 'base64');
      let decompressed = buffer;
      if (entry.compressed) {
        try {
          decompressed = zlib.gunzipSync(buffer);
        } catch (err) {
          console.error(`Failed to decompress asset ${uuid}:`, err);
        }
      }
      
      if (entry.mime.startsWith('text/') || entry.mime === 'application/javascript' || entry.mime === 'image/svg+xml') {
        decodedAssets[uuid] = decompressed.toString('utf8');
      } else {
        decodedAssets[uuid] = `data:${entry.mime};base64,${buffer.toString('base64')}`;
      }
    }

    // Replace uuids in template
    for (const uuid of uuids) {
      template = template.split(uuid).join(decodedAssets[uuid]);
    }

    // Write the unpacked HTML to workspace
    const outputPath = 'c:\\Users\\ASSIMILATE\\Downloads\\Meticulous Research Repositioning\\unpacked_report.html';
    fs.writeFileSync(outputPath, template, 'utf8');

    return new NextResponse(template, {
      headers: {
        'content-type': 'text/html; charset=utf-8'
      }
    });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : String(err)
    return new NextResponse(`Error: ${message}`, { status: 500 });
  }
}
