import { createSidecarProxy } from '@@/sidecar/create-proxy';
import { mountPrefix } from '@@/plugins/manifest';
import { manifest } from '../manifest';

// /api/music/* — auth, then forward to officer-music. No routes of its own and no music knowledge here:
// the whole contract lives in ../sidecar/index.ts, which is where the routes actually are.
//
// ── This used to live in the platform, and that was the bug ──
//
// Until 2026-08-15 the proxy was constructed in `src/servers/api/music/router.ts` — PLATFORM code that
// knew the string 'music' — and this file merely re-exported it. The justification was that
// `api/cliamp/relay.ts` imported `getMusicServerWsUrl` from it, so it could not move.
//
// That justification was three layers of nothing. The relay's functions were only reachable through
// `handlers` entries in server.tsx that were commented out, and its own import there was unused. A dead
// import held a music-named file in the platform, and the second export on it (`getMusicServerUrl`) had
// no callers at all. The relay now lives in ../cliamp/ and takes its URL from here.
//
// ── The prefix is DERIVED, not written ──
//
// It was the literal '/api/music', and that is wrong in a way that only shows up for someone else's
// plugin. The proxy strips `prefix.length` characters to build the sidecar path, so a hardcoded
// '/api/music' (10 chars) is correct only because `mountPrefix` happens to return `/music` for a
// first-party publisher. The same plugin published by anyone else mounts at `/api/p/<publisher>/music`
// and would forward `/alice/music/stream` to a sidecar expecting `/stream`.
//
// `mountPrefix` is the ONE function allowed to know about provenance, so the prefix comes from it. A
// literal here is that rule being broken quietly, which is exactly how first-party and third-party
// become two systems with only one of them tested.
//
// `appName` is passed as a literal because this file cannot see its own directory name. That is a real
// gap — the platform imports `router.ts` and reads `router`, so there is nowhere to inject it — and the
// day a plugin's router needs its own identity for anything else, `api/router.ts` should export a
// factory the installer calls instead. Recorded rather than worked around.
const proxy = createSidecarProxy({
  name: 'music',
  prefix: `/api${mountPrefix({ appName: 'music', manifest })}`,
  // A from-scratch reindex holds the connection open for minutes with no bytes flowing; the default 60s
  // idle drop would kill it. Applied to the whole prefix — the proxy must not know which routes are slow.
  timeoutSeconds: 1800,
});

export const router = proxy.router;

/** The sidecar as a `ws://` base. Used by ../cliamp/relay.ts, and by nothing else. */
export const getMusicServerWsUrl = proxy.getWsUrl;
