import { NextResponse } from 'next/server';
import { exec } from 'child_process';
import util from 'util';
import fs from 'fs-extra';
import path from 'path';
import { TorrentCreationResponse } from '@/types';

const execPromise = util.promisify(exec);

interface ExecError extends Error {
    stdout?: string;
    stderr?: string;
}

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 parentDir = path.dirname(albumPath);
        const albumDirName = path.basename(albumPath);

        // Command: mkbrr create <folder> -P red
        // Run in parent directory so the torrent file is created there
        const command = `mkbrr create "${albumDirName}" -P red`;

        console.log('Running command:', command, 'in', parentDir);

        const { stdout, stderr } = await execPromise(command, { cwd: parentDir });

        // Expected torrent file path
        let torrentPath = path.join(parentDir, `${albumDirName}.torrent`);

        if (!await fs.pathExists(torrentPath)) {
            console.log(`Expected torrent file not found at: ${torrentPath}`);
            console.log('Listing files in parent directory to find match...');

            const files = await fs.readdir(parentDir);
            console.log('Files in directory:', files);

            // Try to find a .torrent file that was created very recently (last 10 seconds)
            // and looks related (contains part of the name or just is a torrent file)
            const recentTorrent = (await Promise.all(files
                .filter(f => f.endsWith('.torrent'))
                .map(async f => {
                    const stat = await fs.stat(path.join(parentDir, f));
                    return { name: f, mtime: stat.mtimeMs };
                })
            ))
                .sort((a, b) => b.mtime - a.mtime)[0]; // Sort by newest

            if (recentTorrent) {
                console.log(`Found recent torrent file: ${recentTorrent.name}`);
                torrentPath = path.join(parentDir, recentTorrent.name);
            }
        }

        if (await fs.pathExists(torrentPath)) {
            const torrentData = await fs.readFile(torrentPath);
            const response: TorrentCreationResponse = {
                success: true,
                output: stdout,
                filename: path.basename(torrentPath),
                data: torrentData.toString('base64')
            };
            return NextResponse.json(response);
        } else {
            const response: TorrentCreationResponse = {
                success: false,
                output: stdout,
                errorOutput: stderr || 'Torrent file not found after generation. Check server logs for file listing.',
                error: 'Torrent file not found'
            };
            return NextResponse.json(response);
        }

    } catch (error) {
        console.error('Error creating torrent:', error);
        const execError = error as ExecError;
        return NextResponse.json({
            error: 'Failed to create torrent',
            details: execError.message,
            output: execError.stdout,
            errorOutput: execError.stderr
        }, { status: 500 });
    }
}
