"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const events = require("./fetch-virtual-server-J6SUa9HS.cjs");
const GATEWAY_URL = "https://napster.brett-lamy.workers.dev";
const DOWNLOADS_DIR = "/home/user/Desktop/Napster Downloads";
const BRIDGE_DIR = "/home/user/.winamp";
const COMMAND_PATH = `${BRIDGE_DIR}/command.json`;
const VMP3_MAGIC = "NAPSTER-VMP3/1";
function ok(stdout) {
  return { stdout, stderr: "", exitCode: 0 };
}
function err(stderr, exitCode = 1) {
  return { stdout: "", stderr, exitCode };
}
function fetchNet(url, options = {}) {
  return events.networkFetch(url, options, events.getDefaultNetworkController());
}
function getIdToken() {
  var _a, _b;
  const bridge = (_b = (_a = globalThis.almostOS) == null ? void 0 : _a.soundcloud) == null ? void 0 : _b.getIdToken;
  return (bridge == null ? void 0 : bridge()) ?? null;
}
function decodeJwtPayload(jwt) {
  const payload = jwt.split(".")[1] ?? "";
  const padded = payload.replace(/-/g, "+").replace(/_/g, "/").padEnd(payload.length + (4 - payload.length % 4) % 4, "=");
  try {
    return JSON.parse(atob(padded));
  } catch {
    return {};
  }
}
function normalize(raw) {
  var _a;
  return {
    title: raw.title ?? "Untitled",
    artist: ((_a = raw.user) == null ? void 0 : _a.username) ?? "Unknown Artist",
    url: raw.permalink_url ?? "",
    artwork: raw.artwork_url ?? null,
    duration: raw.duration ?? 0
  };
}
async function apiGet(path, params) {
  const token = getIdToken();
  if (!token) throw new Error("Not signed in to almost-os yet — reload the desktop and try again.");
  const search = new URLSearchParams();
  for (const [k, v] of Object.entries(params)) search.set(k, String(v));
  const res = await fetchNet(`${GATEWAY_URL}/sc${path}?${search.toString()}`, {
    headers: { Authorization: `Bearer ${token}`, Accept: "application/json; charset=utf-8" }
  });
  if (res.status === 401) throw new Error("almost-os session expired — reload the desktop and try again.");
  if (!res.ok) throw new Error(`SoundCloud API ${res.status}`);
  return await res.json();
}
function unwrap(data) {
  return Array.isArray(data) ? data : data.collection ?? [];
}
async function searchTracks(query, limit = 20) {
  const data = await apiGet("/tracks", {
    q: query,
    limit,
    linked_partitioning: "true"
  });
  return unwrap(data).filter((t) => t.kind === void 0 || t.kind === "track").map(normalize);
}
async function resolveTrack(url) {
  const raw = await apiGet("/resolve", { url });
  if (!raw || typeof raw.id !== "number") throw new Error("URL did not resolve to a track.");
  return normalize(raw);
}
async function toTrack(target) {
  if (/^https?:\/\//.test(target)) {
    try {
      return await resolveTrack(target);
    } catch {
      const slug = decodeURIComponent(target.split("?")[0].split("/").filter(Boolean).pop() ?? target);
      return { title: slug.replace(/-/g, " "), artist: "SoundCloud", url: target, artwork: null, duration: 0 };
    }
  }
  const results = await searchTracks(target, 1);
  if (results.length === 0) throw new Error(`No results for "${target}".`);
  return results[0];
}
function sanitize(part) {
  return part.replace(/[\\/:*?"<>|]/g, "-").replace(/\s+/g, " ").trim().slice(0, 80);
}
function writeVirtualMp3(vfs, track) {
  if (!vfs.existsSync(DOWNLOADS_DIR)) vfs.mkdirSync(DOWNLOADS_DIR, { recursive: true });
  const file = `${sanitize(track.artist || "Unknown Artist")} - ${sanitize(track.title || "Untitled")}.mp3`;
  const payload = {
    url: track.url,
    title: track.title,
    artist: track.artist,
    artwork: track.artwork,
    duration: track.duration,
    downloadedAt: Date.now()
  };
  const path = `${DOWNLOADS_DIR}/${file}`;
  vfs.writeFileSync(path, `${VMP3_MAGIC}
${JSON.stringify(payload, null, 2)}
`);
  return path;
}
function sendPlayerCommand(vfs, action, track) {
  if (!vfs.existsSync(BRIDGE_DIR)) vfs.mkdirSync(BRIDGE_DIR, { recursive: true });
  vfs.writeFileSync(
    COMMAND_PATH,
    JSON.stringify({
      id: `${Date.now()}-${Math.round(Math.random() * 1e6)}`,
      action,
      url: track == null ? void 0 : track.url,
      title: track == null ? void 0 : track.title,
      artist: track == null ? void 0 : track.artist
    })
  );
}
function formatTrackList(tracks) {
  if (tracks.length === 0) return "No results.\n";
  return tracks.map((t, i) => `${String(i + 1).padStart(2)}. ${t.artist} — ${t.title}
    ${t.url}`).join("\n") + "\n";
}
async function runSoundCloudCommand(args, _ctx, vfs, _keychain) {
  const sub = args[0];
  const rest = args.slice(1);
  try {
    switch (sub) {
      case void 0:
      case "help":
      case "--help":
      case "-h":
        return ok(
          [
            "napster — SoundCloud for almost-os (Napster 4.0 + Winamp)",
            "",
            "No sign-in needed — you're already logged into almost-os, and the",
            "napster gateway trusts that same login.",
            "",
            "Usage:",
            "  napster whoami                           Show the signed-in user",
            "  napster search <query…>                  Search tracks",
            "  napster resolve <url>                    Resolve a share URL",
            "  napster download <url|query>             Save a virtual mp3 to the desktop",
            "  napster play <url|query>                 Play in Winamp now",
            "  napster queue <url|query>                Add to the Winamp queue",
            "  napster next | prev | toggle | stop      Transport control",
            ""
          ].join("\n")
        );
      case "whoami": {
        const token = getIdToken();
        if (!token) return err("Not signed in to almost-os yet — reload the desktop and try again.\n");
        const claims = decodeJwtPayload(token);
        const who = typeof claims.email === "string" ? claims.email : typeof claims.name === "string" ? claims.name : "you";
        return ok(`${who} (signed in via almost-os)
`);
      }
      case "search": {
        if (rest.length === 0) return err("Usage: napster search <query>\n");
        const tracks = await searchTracks(rest.join(" "));
        return ok(formatTrackList(tracks));
      }
      case "resolve": {
        if (!rest[0]) return err("Usage: napster resolve <url>\n");
        const track = await resolveTrack(rest[0]);
        return ok(`${track.artist} — ${track.title}
${track.url}
`);
      }
      case "download": {
        if (rest.length === 0) return err("Usage: napster download <url|query>\n");
        const track = await toTrack(rest.join(" "));
        const path = writeVirtualMp3(vfs, track);
        return ok(`⬇ Downloaded ${track.artist} — ${track.title}
   ${path}
`);
      }
      case "play": {
        if (rest.length === 0) return err("Usage: napster play <url|query>\n");
        const track = await toTrack(rest.join(" "));
        sendPlayerCommand(vfs, "play", track);
        return ok(`▶ Playing in Winamp: ${track.artist} — ${track.title}
`);
      }
      case "queue": {
        if (rest.length === 0) return err("Usage: napster queue <url|query>\n");
        const track = await toTrack(rest.join(" "));
        sendPlayerCommand(vfs, "queue", track);
        return ok(`＋ Queued in Winamp: ${track.artist} — ${track.title}
`);
      }
      case "next":
        sendPlayerCommand(vfs, "next");
        return ok("⏭ Next\n");
      case "prev":
        sendPlayerCommand(vfs, "prev");
        return ok("⏮ Previous\n");
      case "toggle":
        sendPlayerCommand(vfs, "toggle");
        return ok("⏯ Toggled play/pause\n");
      case "stop":
        sendPlayerCommand(vfs, "stop");
        return ok("⏹ Stopped\n");
      default:
        return err(`napster: unknown command '${sub}'. Try \`napster help\`.
`);
    }
  } catch (e) {
    return err(`napster: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
exports.runSoundCloudCommand = runSoundCloudCommand;
//# sourceMappingURL=soundcloud-command-D7d0loRW.cjs.map
