import express from 'express';
import multer from 'multer';
import Busboy from 'busboy';
import dotenv from 'dotenv';
import { commit } from '@huggingface/hub';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';

dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;

// --- CẤU HÌNH PATH ---
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const TEMP_DIR = path.join(__dirname, 'temp_uploads');
const PUBLIC_DIR = path.join(__dirname, 'public'); // Đường dẫn tới thư mục Frontend

// Tạo thư mục tạm nếu chưa có
fs.ensureDirSync(TEMP_DIR);

// --- QUAN TRỌNG: CẤU HÌNH PHỤC VỤ FILE TĨNH ---
// Khi user vào http://localhost:3000, express sẽ trả về index.html trong public
app.use(express.static(PUBLIC_DIR));

// --- HÀM HELPER: UPLOAD LÊN HF ---
async function uploadToHuggingFace(filesData, methodLabel) {
    const operations = filesData.map(file => {
        const fileBuffer = fs.readFileSync(file.path);
        return {
            operation: "addOrUpdate",
            path: `uploads/${file.originalName}`,
            content: new Blob([fileBuffer])
        };
    });

    console.log(`🚀 [${methodLabel}] Đang commit ${filesData.length} file lên HF...`);

    const result = await commit({
        repo: {
  type: "dataset",
  name: process.env.HF_REPO_ID
        },
          credentials: { accessToken: process.env.HF_TOKEN },
        title: `Fullstack Upload via ${methodLabel}: ${new Date().toLocaleString()}`,
        operations: operations,
    });

    // Dọn dẹp file rác
    filesData.forEach(f => {
        if (fs.existsSync(f.path)) fs.unlinkSync(f.path);
    });

    return result.commitUrl;
}

// --- API 1: MULTER (NORMAL MODE) ---
const multerStorage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, TEMP_DIR),
    filename: (req, file, cb) => cb(null, `multer-${Date.now()}-${file.originalname}`)
});
const uploadMulter = multer({ storage: multerStorage });

app.post('/api/upload-multer', uploadMulter.array('files'), async (req, res) => {
    try {
        if (!req.files || req.files.length === 0) return res.status(400).json({ error: "Chưa chọn file" });

        const filesData = req.files.map(f => ({
            path: f.path,
            originalName: f.originalname
        }));

        const commitUrl = await uploadToHuggingFace(filesData, "Multer");
        res.json({ success: true, mode: "Multer", commitUrl });
    } catch (error) {
        console.error("Lỗi Multer:", error);
        res.status(500).json({ error: error.message });
    }
});

// --- API 2: BUSBOY (STREAM MODE - CHO FILE NẶNG) ---
app.post('/api/upload-stream', (req, res) => {
    const busboy = Busboy({ headers: req.headers });
    const writePromises = [];
    const filesData = [];
    const requestId = Date.now();

    busboy.on('file', (fieldname, fileStream, info) => {
        const savePath = path.join(TEMP_DIR, `stream-${requestId}-${info.filename}`);
        const writeStream = fs.createWriteStream(savePath);
        fileStream.pipe(writeStream);

        const p = new Promise((resolve, reject) => {
            writeStream.on('finish', () => {
                filesData.push({ path: savePath, originalName: info.filename });
                resolve();
            });
            writeStream.on('error', reject);
        });
        writePromises.push(p);
    });

    busboy.on('finish', async () => {
        try {
            await Promise.all(writePromises);
            if (filesData.length === 0) return res.status(400).json({ error: "Chưa chọn file" });

            const commitUrl = await uploadToHuggingFace(filesData, "Stream");
            res.json({ success: true, mode: "Stream", commitUrl });
        } catch (error) {
            console.error("Lỗi Stream:", error);
            filesData.forEach(f => fs.removeSync(f.path));
            res.status(500).json({ error: error.message });
        }
    });

    req.pipe(busboy);
});

// --- START SERVER ---
app.listen(PORT, () => {
    console.log(`✅ App Fullstack đang chạy tại http://localhost:${PORT}`);
});
