import { NextResponse } from 'next/server';
import fs from 'fs-extra';
import path from 'path';
import { ProposeRenameResponse, RenameProposal } from '@/types';

export async function POST(request: Request) {
    try {
        const { albumPath } = await request.json();

        if (!albumPath || !(await fs.pathExists(albumPath))) {
            return NextResponse.json({ error: 'Invalid album path' }, { status: 400 });
        }

        const files = await fs.readdir(albumPath);
        const folderName = path.basename(albumPath);
        // Max length for file + folder + separator is 179 (to match frontend check > 179)
        // So max file length = 179 - folderName.length - 1 (separator)
        const maxFileLength = 179 - folderName.length - 1;

        const problematicFiles: RenameProposal[] = [];
        const allFiles: RenameProposal[] = [];

        for (const file of files) {
            const filePath = path.join(albumPath, file);
            const stat = await fs.stat(filePath);

            if (stat.isFile()) {
                const ext = path.extname(file);
                const name = path.basename(file, ext);

                // Strategy 1: Remove Brackets []
                const nameNoBrackets = name.replace(/\[.*?\]/g, '').replace(/\s+/g, ' ').trim();
                const fileNoBrackets = nameNoBrackets + ext;

                // Strategy 2: Remove Parentheses ()
                const nameNoParens = name.replace(/\(.*?\)/g, '').replace(/\s+/g, ' ').trim();
                const fileNoParens = nameNoParens + ext;

                // Strategy 3: Remove Both
                const nameClean = name.replace(/\[.*?\]/g, '').replace(/\(.*?\)/g, '').replace(/\s+/g, ' ').trim();
                const fileClean = nameClean + ext;

                // Strategy 4: Truncate (fallback if others fail or just as an option)
                // We need to truncate 'name' so that name + ext <= maxFileLength
                const maxNameLength = maxFileLength - ext.length;
                let nameTruncated = name;
                if (name.length > maxNameLength) {
                    nameTruncated = name.substring(0, maxNameLength).trim();
                }
                const fileTruncated = nameTruncated + ext;

                const proposal: RenameProposal = {
                    original: file,
                    strategies: {
                        remove_brackets: fileNoBrackets.length <= maxFileLength ? fileNoBrackets : null,
                        remove_parens: fileNoParens.length <= maxFileLength ? fileNoParens : null,
                        remove_both: fileClean.length <= maxFileLength ? fileClean : null,
                        truncate: fileTruncated
                    }
                };

                allFiles.push(proposal);

                // Check if file exceeds limit
                if (file.length > maxFileLength) {
                    problematicFiles.push(proposal);
                }
            }
        }

        const response: ProposeRenameResponse = {
            success: true,
            problematicFiles,
            allFiles,
            maxFileLength
        };

        return NextResponse.json(response);

    } catch (error) {
        console.error('Error proposing renames:', error);
        return NextResponse.json({ error: 'Failed to propose renames' }, { status: 500 });
    }
}
