// server.js
import express from 'express';
import axios from 'axios';
import fs from 'fs';
import path from 'path';
import mime from 'mime-types';
import { pipeline } from 'stream/promises';

const app = express();
const PORT = 3000;
const CACHE_DIR = './cache';

if (!fs.existsSync(CACHE_DIR)) {
  fs.mkdirSync(CACHE_DIR);
}


// Stream & cache an toàn
app.get('/stream/:filename', async (req, res) => {
  const { filename } = req.params;
  const cachedPath = path.join(CACHE_DIR, filename);
  const tempPath = cachedPath + '.part';
  const mimeType = mime.lookup(filename) || 'application/octet-stream';

  if (fs.existsSync(cachedPath)) {
    const stat = fs.statSync(cachedPath);
    res.writeHead(200, {
      'Content-Type': mimeType,
      'Content-Disposition': `inline; filename="${filename}"`,
      'Content-Length': stat.size,
      'Accept-Ranges': 'bytes',
    });
    fs.createReadStream(cachedPath).pipe(res);
    return;
  }

  const HF_URL = `https://huggingface.co/datasets/TwanAPI/DataTwan/resolve/main/${encodeURIComponent(filename)}`;

  try {
    const response = await axios.get(HF_URL, {
      responseType: 'stream',
      headers: { 'User-Agent': 'Node.js Server' },
    });

    const writer = fs.createWriteStream(tempPath);
    await pipeline(response.data, writer);
    fs.renameSync(tempPath, cachedPath);

    const stat = fs.statSync(cachedPath);
    res.writeHead(200, {
      'Content-Type': mimeType,
      'Content-Disposition': `inline; filename="${filename}"`,
      'Content-Length': stat.size,
      'Accept-Ranges': 'bytes',
    });
    fs.createReadStream(cachedPath).pipe(res);
  } catch (err) {
    console.error('❌ Lỗi khi stream:', err.message);
    res.status(500).send('Không thể stream file từ Hugging Face.');
  }
});

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