import { NextResponse } from 'next/server';
import path from 'path';
import fs from 'fs';
/**
 * Local asset server for devdoc dev mode
 * 
 * Serves assets from the user's project folder (STARTER_PATH/assets/)
 * This allows /assets/images/logo.png to work in local development
 */ export async function GET(request, { params }) {
    try {
        const { path: pathSegments } = await params;
        if (!pathSegments || pathSegments.length === 0) {
            return NextResponse.json({
                error: 'Invalid asset path'
            }, {
                status: 400
            });
        }
        // Get the project path from environment
        const projectPath = process.env.STARTER_PATH;
        if (!projectPath) {
            return NextResponse.json({
                error: 'Not in local development mode'
            }, {
                status: 404
            });
        }
        // Build file path - assets are in projectPath/assets/
        const assetPath = pathSegments.join('/');
        const filePath = path.join(projectPath, 'assets', assetPath);
        // Security: ensure we're not escaping the assets directory
        const resolvedPath = path.resolve(filePath);
        const assetsDir = path.resolve(path.join(projectPath, 'assets'));
        if (!resolvedPath.startsWith(assetsDir)) {
            return NextResponse.json({
                error: 'Invalid path'
            }, {
                status: 403
            });
        }
        // Check if file exists
        if (!fs.existsSync(resolvedPath)) {
            // Also try without 'assets' prefix (for /assets/images/x.png -> images/x.png)
            const altPath = path.join(projectPath, assetPath);
            const resolvedAltPath = path.resolve(altPath);
            if (resolvedAltPath.startsWith(path.resolve(projectPath)) && fs.existsSync(resolvedAltPath)) {
                const fileBuffer = fs.readFileSync(resolvedAltPath);
                const contentType = getContentType(assetPath);
                return new NextResponse(fileBuffer, {
                    status: 200,
                    headers: {
                        'Content-Type': contentType,
                        'Cache-Control': 'no-cache'
                    }
                });
            }
            return NextResponse.json({
                error: 'Asset not found',
                path: assetPath
            }, {
                status: 404
            });
        }
        const fileBuffer = fs.readFileSync(resolvedPath);
        const contentType = getContentType(assetPath);
        return new NextResponse(fileBuffer, {
            status: 200,
            headers: {
                'Content-Type': contentType,
                'Cache-Control': 'no-cache'
            }
        });
    } catch (error) {
        console.error('[Local Assets] Error:', error);
        return NextResponse.json({
            error: 'Failed to serve asset'
        }, {
            status: 500
        });
    }
}
/**
 * Get content type from file extension
 */ function getContentType(fileName) {
    const ext = fileName.split('.').pop()?.toLowerCase();
    const types = {
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif',
        'webp': 'image/webp',
        'svg': 'image/svg+xml',
        'ico': 'image/x-icon',
        'pdf': 'application/pdf',
        'mp4': 'video/mp4',
        'webm': 'video/webm',
        'mp3': 'audio/mpeg',
        'wav': 'audio/wav',
        'woff': 'font/woff',
        'woff2': 'font/woff2',
        'ttf': 'font/ttf',
        'otf': 'font/otf',
        'json': 'application/json',
        'css': 'text/css',
        'js': 'application/javascript'
    };
    return types[ext || ''] || 'application/octet-stream';
}
