const axios = require("axios");
const fs = require("fs");
const path = require("path");

module.exports.zuckbotconfig = {
  name: "scl",
  version: "2.1.0",
  role: 0,
  author: "twan",
  info: "Tìm và tải nhạc SoundCloud",
  Category: "Admin",
  usages: "[tên bài hát | link SoundCloud]",
  cd: 5
};

const CLIENT_ID = "OeDHpok8199e6vW8pnF7SljVEa4tYz6z";
const API = "https://api-v2.soundcloud.com";
const CACHE_DIR = path.join(__dirname, "cache");
if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true });

function msToMinSec(ms) {
  const m = Math.floor(ms / 60000), s = Math.round((ms % 60000) / 1000);
  return `${m}:${String(s).padStart(2, "0")}`;
}

async function searchTrack(q) {
  const { data } = await axios.get(`${API}/search/tracks`, {
    params: { q, client_id: CLIENT_ID, limit: 20 },
    headers: { "User-Agent": "Mozilla/5.0" }
  });
  return (data.collection || []).find(t =>
    t.duration <= 600000 &&
    t.media?.transcodings?.some(tr => tr.format?.protocol === "progressive")
  );
}

async function getStreamUrl(track) {
  const prog = track.media.transcodings.find(t => t.format.protocol === "progressive");
  const { data } = await axios.get(prog.url, { params: { client_id: CLIENT_ID } });
  return data.url;
}

async function download(url, outPath) {
  const res = await axios({ url, method: "GET", responseType: "stream" });
  return new Promise((resolve, reject) => {
    const writer = fs.createWriteStream(outPath);
    res.data.pipe(writer);
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}

module.exports.onRun = async ({ api, event, args }) => {
  const query = args.join(" ").trim();
  if (!query) return api.sendMessage("❗ Nhập tên bài hát.", event.threadID, event.messageID);

  try {
    const track = await searchTrack(query);
    if (!track) return api.sendMessage("❌ Không tìm thấy bài phù hợp.", event.threadID, event.messageID);

    const url = await getStreamUrl(track);
    const filePath = path.join(CACHE_DIR, `${Date.now()}.mp3`);
    await download(url, filePath);

    api.sendMessage({
      body: `${track.title}:${msToMinSec(track.duration)}`,
      attachment: fs.createReadStream(filePath)
    }, event.threadID, () => fs.unlinkSync(filePath), event.messageID);

  } catch (e) {
    api.sendMessage("⚠️ Lỗi khi tải bài hát.", event.threadID, event.messageID);
  }
};