/**
 * dsh-writing-desk host half.
 *
 * Two read/write surfaces over the dsh webServer loopback HTTP API:
 *   1. Materials — the local Markdown notes under each workspace's
 *      `.dsh-notes/` (read-only reference materials).
 *   2. Manuscript — the 正文 written in the workbench, organized as
 *      volumes (卷) and chapters (章) under `<workspace>/写作/`:
 *         写作/第一卷/第一章.md
 *         写作/第一卷/第二章.md
 *         写作/第二卷/第一章.md
 *      Each volume auto-numbers `第N卷`; each volume's chapters restart at
 *      `第一章`. Default chapter names are `第X章` and can be renamed.
 *
 * Kept dependency-free (node builtins only) so the host half loads from any
 * `link:` install location. Writing resolves the target workspace from an
 * explicit `workspaceId` or, failing that, from the active session's cwd.
 */
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

export const name = 'writing-desk';
export const inject = ['webServer'];

const DEFAULT_ROUTE = '/plugins/writing-desk';
const DEFAULT_NOTES_DIR = '.dsh-notes';
const DEFAULT_DRAFTS_DIR = '写作';
const DEFAULT_BOOK = '默认书籍';
const OUTPUT_CONFIG_FILE = '.dsh-writing-desk.json';
const OUTLINE_FILE = '大纲.md';

const MAX_SEARCH_MATCHES = 40;
const SNIPPET_LEN = 160;

/* ------------------------------------------------------------------ *
 * Chinese numeral helpers (第 N 卷 / 第 X 章 auto-numbering)
 * ------------------------------------------------------------------ */

const CN_DIGITS = '零一二三四五六七八九';
const CN_SMALL_UNITS = ['', '十', '百', '千'];
const CN_BIG_UNITS = ['', '万', '亿'];

function sectionToCn(sec) {
  if (sec === 0) return '';
  let out = '';
  let zero = false;
  let v = sec;
  for (let i = 0; i < 4; i++) {
    const d = v % 10;
    v = Math.floor(v / 10);
    if (d === 0) {
      if (out !== '') zero = true;
    } else {
      if (zero) { out = '零' + out; zero = false; }
      out = CN_DIGITS[d] + CN_SMALL_UNITS[i] + out;
    }
  }
  return out;
}

function intToChinese(n) {
  if (!Number.isInteger(n) || n < 0) return String(n);
  if (n === 0) return '零';
  if (n >= 100000000) return String(n);
  let result = '';
  let needZero = false;
  let big = 0;
  while (n > 0) {
    const sec = n % 10000;
    n = Math.floor(n / 10000);
    const secStr = sectionToCn(sec);
    if (secStr !== '') {
      if (needZero) result = '零' + result;
      result = secStr + CN_BIG_UNITS[big] + result;
      needZero = sec < 1000;
    } else if (result !== '') {
      needZero = true;
    }
    big++;
  }
  if (result.startsWith('一十')) result = result.slice(1);
  return result;
}

function chineseToInt(s) {
  if (typeof s !== 'string' || s === '') return NaN;
  if (/^\d+$/.test(s)) return parseInt(s, 10);
  const digitMap = { 零: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 };
  const unitMap = { 十: 10, 百: 100, 千: 1000 };
  let total = 0;
  let section = 0;
  let current = 0;
  for (const ch of s) {
    if (ch === '万') { section = (section + current) * 10000; total += section; section = 0; current = 0; continue; }
    if (ch === '亿') { total = (total + section + current) * 100000000; section = 0; current = 0; continue; }
    if (ch in digitMap) { current = digitMap[ch]; continue; }
    if (ch in unitMap) {
      const unit = unitMap[ch];
      if (current === 0) current = 1;
      section += current * unit;
      current = 0;
      continue;
    }
    return NaN;
  }
  return total + section + current;
}

const NUMERAL = '[零一二三四五六七八九十百千万两\\d]';
const CHAPTER_RE = new RegExp('^第(' + NUMERAL + '+?)章');
// Not anchored at the end: a renamed volume like 第二卷 风起 still numbers as 2.
const VOLUME_RE = new RegExp('^第(' + NUMERAL + '+?)卷');

function volumeNumber(name) {
  const m = VOLUME_RE.exec(name);
  return m ? chineseToInt(m[1]) : NaN;
}

function chapterNumber(filename) {
  const base = String(filename).replace(/\.md$/i, '');
  const m = CHAPTER_RE.exec(base);
  return m ? chineseToInt(m[1]) : NaN;
}

/* ------------------------------------------------------------------ *
 * Notes (reference materials) helpers
 * ------------------------------------------------------------------ */

function stripSuffix(filename) {
  return filename.replace(/\.md$/i, '').replace(/[_-]v?\d+(\.\d+)*$/i, '').trim();
}

async function noteTitle(filePath, fallback) {
  try {
    const data = await readFile(filePath, 'utf8');
    for (const line of data.split(/\r?\n/).slice(0, 12)) {
      const m = line.match(/^\s*#\s+(.+?)\s*$/);
      if (m) return m[1].trim();
    }
    return fallback;
  } catch {
    return fallback;
  }
}

async function listNotes(dir) {
  const notes = [];
  try {
    const entries = await readdir(dir, { withFileTypes: true });
    for (const entry of entries) {
      if (!entry.isFile() || !/\.md$/i.test(entry.name)) continue;
      const filePath = path.join(dir, entry.name);
      let size = 0;
      let updatedAt = 0;
      try {
        const st = await stat(filePath);
        size = st.size;
        updatedAt = st.mtimeMs;
      } catch {
        /* keep defaults */
      }
      notes.push({
        name: entry.name,
        title: await noteTitle(filePath, stripSuffix(entry.name)),
        size,
        updatedAt,
      });
    }
    notes.sort((a, b) => a.title.localeCompare(b.title, 'zh-CN'));
  } catch {
    /* missing dir → empty list */
  }
  return notes;
}

const WINDOWS_RESERVED = /[<>:"|?*\u0000-\u001f]/;

/** Reject names that Windows filesystems mishandle: reserved chars, separators,
 *  empty/. /.., and trailing dots or spaces (silently stripped by Windows). */
function isInvalidName(name) {
  if (typeof name !== 'string' || name === '' || name === '.' || name === '..') return true;
  if (WINDOWS_RESERVED.test(name)) return true;
  if (/[\\/]/.test(name)) return true;
  if (/[. ]$/.test(name)) return true;
  return false;
}

function safeNotePath(dir, name) {
  if (isInvalidName(name)) return null;
  const base = path.basename(name);
  if (base !== name || !/\.md$/i.test(base)) return null;
  return path.join(dir, base);
}

async function readNote(dir, name) {
  const filePath = safeNotePath(dir, name);
  if (filePath === null) return { ok: false, error: 'invalid note name' };
  try {
    const content = await readFile(filePath, 'utf8');
    return { ok: true, name: path.basename(filePath), content };
  } catch {
    return { ok: false, error: 'note not found' };
  }
}

async function pathExists(p) {
  try { await stat(p); return true; } catch { return false; }
}

/** Copy an arbitrary local file into the notes dir (import). Name collisions
 *  are de-duplicated with a numeric suffix; the source path is read by the host
 *  process (a local single-user tool), never from the browser. */
async function importNote(notesDir, sourcePath) {
  if (typeof sourcePath !== 'string' || sourcePath === '') return { ok: false, error: 'invalid source path' };
  try {
    const data = await readFile(sourcePath);
    const base = path.basename(sourcePath);
    await mkdir(notesDir, { recursive: true });
    let target = path.join(notesDir, base);
    let n = 1;
    while (await pathExists(target)) {
      const ext = path.extname(base);
      const stem = ext ? base.slice(0, base.length - ext.length) : base;
      target = path.join(notesDir, stem + '-' + n + ext);
      n++;
    }
    await atomicWrite(target, data);
    return { ok: true, name: path.basename(target), path: target };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

/** Save file content (from a browser file picker) as a note in the notes dir.
 *  Extension is normalized to .md so it appears in the notes list. */
async function saveNote(notesDir, name, content) {
  if (typeof name !== 'string' || name === '') return { ok: false, error: 'invalid note name' };
  const rawBase = name.replace(/\.[^.]+$/i, '');
  const base = isInvalidName(rawBase) ? 'note' : rawBase;
  try {
    await mkdir(notesDir, { recursive: true });
    let target = path.join(notesDir, base + '.md');
    let n = 1;
    while (await pathExists(target)) {
      target = path.join(notesDir, `${base}-${n}.md`);
      n++;
    }
    await atomicWrite(target, String(content ?? ''));
    return { ok: true, name: path.basename(target), path: target };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

/** Open a folder in the system file manager. Fire-and-forget: we resolve on
 *  successful spawn (not on exit), because explorer.exe / open / xdg-open are
 *  UI launchers that often exit with a non-zero code even after opening the
 *  folder. Windows goes through `cmd /c start` which reliably handles the
 *  Unicode 写作 path. */
function openDir(dir) {
  return new Promise((resolve) => {
    const platform = process.platform;
    let cmd;
    let args;
    if (platform === 'win32') {
      cmd = 'cmd.exe';
      args = ['/c', 'start', '', dir];
    } else if (platform === 'darwin') {
      cmd = 'open';
      args = [dir];
    } else {
      cmd = 'xdg-open';
      args = [dir];
    }
    let child;
    try {
      child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
    } catch (error) {
      resolve({ ok: false, error: error instanceof Error ? error.message : String(error) });
      return;
    }
    let settled = false;
    child.on('error', (error) => {
      if (settled) return;
      settled = true;
      resolve({ ok: false, error: error instanceof Error ? error.message : String(error) });
    });
    child.on('spawn', () => {
      if (settled) return;
      settled = true;
      try { child.unref(); } catch { /* ignore */ }
      resolve({ ok: true });
    });
    // Fallback: if neither event fired promptly, still treat it as started.
    setTimeout(() => {
      if (settled) return;
      settled = true;
      try { child.unref(); } catch { /* ignore */ }
      resolve({ ok: true });
    }, 1000);
  });
}

/** Atomic write: write to a temp sibling then rename over the target, so a
 *  crash mid-write can never leave a truncated .md. */
async function atomicWrite(filePath, data) {
  const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
  await writeFile(tmp, data, 'utf8');
  try {
    await rename(tmp, filePath);
  } catch (error) {
    try { await unlink(tmp); } catch { /* ignore */ }
    throw error;
  }
}

/* ---- output directory config (per workspace) ---- */

async function loadOutputConfig(wsPath) {
  try {
    const data = await readFile(path.join(wsPath, OUTPUT_CONFIG_FILE), 'utf8');
    const cfg = JSON.parse(data);
    return cfg && typeof cfg === 'object' ? cfg : {};
  } catch {
    return {};
  }
}

async function saveOutputConfig(wsPath, cfg) {
  await writeFile(path.join(wsPath, OUTPUT_CONFIG_FILE), JSON.stringify(cfg, null, 2), 'utf8');
}

/** Resolve the manuscript storage root: a user-set custom dir, else 写作/. */
async function resolveOutputDir(ws) {
  const cfg = await loadOutputConfig(ws.path);
  const out = cfg && cfg.outputDir;
  if (typeof out === 'string' && out.trim() !== '') return out.trim();
  return path.join(ws.path, DEFAULT_DRAFTS_DIR);
}

async function setOutputDir(ws, dir) {
  const cfg = await loadOutputConfig(ws.path);
  if (typeof dir === 'string' && dir.trim() !== '') {
    cfg.outputDir = dir.trim();
  } else {
    delete cfg.outputDir;
  }
  try {
    await saveOutputConfig(ws.path, cfg);
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
  return { ok: true, outputDir: cfg.outputDir || path.join(ws.path, DEFAULT_DRAFTS_DIR) };
}

function snippetOf(line, query) {
  const idx = line.toLowerCase().indexOf(query.toLowerCase());
  if (idx >= 0) {
    const start = Math.max(0, idx - 30);
    return (start > 0 ? '…' : '') + line.slice(start, start + SNIPPET_LEN) + (line.length > start + SNIPPET_LEN ? '…' : '');
  }
  return line.slice(0, SNIPPET_LEN);
}

async function searchNotes(workspaces, query, limit) {
  const matches = [];
  const q = String(query ?? '').trim();
  if (q === '') return matches;
  outer: for (const ws of workspaces) {
    for (const note of ws.notes) {
      if (matches.length >= limit) break outer;
      let content;
      try {
        content = await readFile(path.join(ws.notesDir, note.name), 'utf8');
      } catch {
        continue;
      }
      const lines = content.split(/\r?\n/);
      for (let i = 0; i < lines.length; i++) {
        if (!lines[i].toLowerCase().includes(q.toLowerCase())) continue;
        matches.push({
          workspaceId: ws.workspaceId,
          workspaceName: ws.name,
          name: note.name,
          title: note.title,
          notesDir: ws.notesDir,
          line: i + 1,
          snippet: snippetOf(lines[i], q),
        });
        if (matches.length >= limit) break outer;
      }
    }
  }
  return matches;
}

/* ------------------------------------------------------------------ *
 * Manuscript (卷 / 章) helpers
 * ------------------------------------------------------------------ */

/** Force `name` to be a direct child of `dir` (rejects separators/traversal). */
function safeChild(dir, name) {
  if (isInvalidName(name)) return null;
  const base = path.basename(name);
  if (base !== name) return null;
  return path.join(dir, base);
}

/** One-time migration: the old layout kept 卷 directly under 写作/. Move any
 *  directory whose name parses as a 卷 number into a 默认书籍/ book so the new
 *  book → volume → chapter hierarchy stays consistent. Non-destructive move. */
async function migrateLegacyVolumes(draftsDir) {
  try {
    const entries = await readdir(draftsDir, { withFileTypes: true });
    const legacy = entries.filter((e) => e.isDirectory() && Number.isFinite(volumeNumber(e.name)));
    if (legacy.length === 0) return;
    const bookDir = path.join(draftsDir, DEFAULT_BOOK);
    await mkdir(bookDir, { recursive: true });
    for (const vol of legacy) {
      try { await rename(path.join(draftsDir, vol.name), path.join(bookDir, vol.name)); } catch { /* ignore */ }
    }
  } catch { /* ignore */ }
}

async function listBooks(draftsDir) {
  await migrateLegacyVolumes(draftsDir);
  const books = [];
  try {
    const entries = await readdir(draftsDir, { withFileTypes: true });
    const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
    dirs.sort((a, b) => a.localeCompare(b, 'zh-CN'));
    for (const name of dirs) {
      const bookDir = path.join(draftsDir, name);
      books.push({ name, path: bookDir, volumes: await listVolumes(bookDir) });
    }
  } catch {
    /* missing dir → empty list */
  }
  return books;
}

async function createBook(draftsDir, name) {
  const bookDir = safeChild(draftsDir, name);
  if (bookDir === null) return { ok: false, error: 'invalid book name' };
  try {
    await mkdir(bookDir, { recursive: true });
    return { ok: true, name };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

async function renameBook(draftsDir, oldName, newName) {
  const oldPath = safeChild(draftsDir, oldName);
  const newPath = safeChild(draftsDir, newName);
  if (oldPath === null || newPath === null) return { ok: false, error: 'invalid book name' };
  try {
    await rename(oldPath, newPath);
    return { ok: true, name: newName };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

async function listChapters(volumeDir) {
  const chapters = [];
  try {
    const entries = await readdir(volumeDir, { withFileTypes: true });
    for (const entry of entries) {
      if (!entry.isFile() || !/\.md$/i.test(entry.name)) continue;
      let size = 0;
      let updatedAt = 0;
      try {
        const st = await stat(path.join(volumeDir, entry.name));
        size = st.size;
        updatedAt = st.mtimeMs;
      } catch {
        /* keep defaults */
      }
      chapters.push({ name: entry.name, title: entry.name.replace(/\.md$/i, ''), size, updatedAt });
    }
    chapters.sort((a, b) => {
      const an = chapterNumber(a.name);
      const bn = chapterNumber(b.name);
      if (Number.isFinite(an) && Number.isFinite(bn) && an !== bn) return an - bn;
      return a.title.localeCompare(b.title, 'zh-CN');
    });
  } catch {
    /* missing dir → empty list */
  }
  return chapters;
}

async function listVolumes(draftsDir) {
  const volumes = [];
  try {
    const entries = await readdir(draftsDir, { withFileTypes: true });
    const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
    dirs.sort((a, b) => {
      const an = volumeNumber(a);
      const bn = volumeNumber(b);
      if (Number.isFinite(an) && Number.isFinite(bn) && an !== bn) return an - bn;
      return a.localeCompare(b, 'zh-CN');
    });
    for (const name of dirs) {
      volumes.push({ name, chapters: await listChapters(path.join(draftsDir, name)) });
    }
  } catch {
    /* missing dir → empty list */
  }
  return volumes;
}

async function nextVolumeName(draftsDir) {
  let max = 0;
  try {
    for (const entry of await readdir(draftsDir, { withFileTypes: true })) {
      if (!entry.isDirectory()) continue;
      const n = volumeNumber(entry.name);
      if (Number.isFinite(n)) max = Math.max(max, n);
    }
  } catch {
    /* ignore */
  }
  return '第' + intToChinese(max + 1) + '卷';
}

async function nextChapterName(volumeDir) {
  let max = 0;
  try {
    for (const entry of await readdir(volumeDir, { withFileTypes: true })) {
      if (!entry.isFile() || !/\.md$/i.test(entry.name)) continue;
      const n = chapterNumber(entry.name);
      if (Number.isFinite(n)) max = Math.max(max, n);
    }
  } catch {
    /* ignore */
  }
  return '第' + intToChinese(max + 1) + '章';
}

async function createVolume(draftsDir) {
  try {
    await mkdir(draftsDir, { recursive: true });
    const name = await nextVolumeName(draftsDir);
    await mkdir(path.join(draftsDir, name), { recursive: true });
    return { ok: true, name };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

async function createChapter(draftsDir, volume) {
  const volumeDir = safeChild(draftsDir, volume);
  if (volumeDir === null) return { ok: false, error: 'invalid volume' };
  try {
    const name = await nextChapterName(volumeDir);
    await mkdir(volumeDir, { recursive: true });
    await writeFile(path.join(volumeDir, name + '.md'), '', 'utf8');
    return { ok: true, name: name + '.md' };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

async function readChapter(draftsDir, volume, chapter) {
  const volumeDir = safeChild(draftsDir, volume);
  const filePath = volumeDir === null ? null : safeChild(volumeDir, chapter);
  if (filePath === null) return { ok: false, error: 'invalid chapter' };
  try {
    const content = await readFile(filePath, 'utf8');
    return { ok: true, name: chapter, content, path: filePath };
  } catch {
    // A brand-new chapter is not an error: return an empty draft.
    return { ok: true, name: chapter, content: '', path: filePath };
  }
}

async function writeChapter(draftsDir, volume, chapter, content) {
  const volumeDir = safeChild(draftsDir, volume);
  const filePath = volumeDir === null ? null : safeChild(volumeDir, chapter);
  if (filePath === null) return { ok: false, error: 'invalid chapter' };
  try {
    await mkdir(volumeDir, { recursive: true });
    await atomicWrite(filePath, String(content ?? ''));
    return { ok: true, name: chapter, path: filePath };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

/** Merge an entire book (all volumes, all chapters) into one Markdown string. */
async function exportBook(draftsDir, book) {
  const bookDir = safeChild(draftsDir, book);
  if (bookDir === null) return { ok: false, error: 'invalid book' };
  const volumes = await listVolumes(bookDir);
  let md = '# ' + book + '\n\n';
  for (const vol of volumes) {
    md += '## ' + vol.name + '\n\n';
    for (const ch of vol.chapters) {
      const r = await readChapter(bookDir, vol.name, ch.name);
      md += '### ' + ch.title + '\n\n' + (r.content || '').replace(/\s+$/, '') + '\n\n';
    }
  }
  return { ok: true, book, content: md, volumes: volumes.length, chapters: volumes.reduce((n, v) => n + v.chapters.length, 0) };
}

/** Read the per-book outline file (写作/<book>/大纲.md). Missing = empty. */
async function readOutline(draftsDir, book) {
  const bookDir = safeChild(draftsDir, book);
  if (bookDir === null) return { ok: false, error: 'invalid book' };
  try {
    const content = await readFile(path.join(bookDir, OUTLINE_FILE), 'utf8');
    return { ok: true, content };
  } catch {
    return { ok: true, content: '' };
  }
}

/** Write the per-book outline file (atomic). */
async function writeOutline(draftsDir, book, content) {
  const bookDir = safeChild(draftsDir, book);
  if (bookDir === null) return { ok: false, error: 'invalid book' };
  try {
    await mkdir(bookDir, { recursive: true });
    await atomicWrite(path.join(bookDir, OUTLINE_FILE), String(content ?? ''));
    return { ok: true, path: path.join(bookDir, OUTLINE_FILE) };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

async function renameVolume(draftsDir, oldName, newName) {
  const oldPath = safeChild(draftsDir, oldName);
  const newPath = safeChild(draftsDir, newName);
  if (oldPath === null || newPath === null) return { ok: false, error: 'invalid name' };
  try {
    await rename(oldPath, newPath);
    return { ok: true, name: newName };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

async function renameChapter(draftsDir, volume, oldName, newName) {
  const volumeDir = safeChild(draftsDir, volume);
  const oldPath = volumeDir === null ? null : safeChild(volumeDir, oldName);
  const fixed = /\.md$/i.test(newName) ? newName : newName + '.md';
  const newPath = volumeDir === null ? null : safeChild(volumeDir, fixed);
  if (oldPath === null || newPath === null) return { ok: false, error: 'invalid name' };
  try {
    await rename(oldPath, newPath);
    return { ok: true, name: fixed };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

/* ------------------------------------------------------------------ *
 * HTTP plumbing
 * ------------------------------------------------------------------ */

async function readBody(req) {
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
    size += buf.length;
    if (size > 4 * 1024 * 1024) throw new Error('body too large');
    chunks.push(buf);
  }
  if (chunks.length === 0) return {};
  try {
    return JSON.parse(Buffer.concat(chunks).toString('utf8'));
  } catch {
    return {};
  }
}

function sendJson(res, status, value) {
  res.writeHead(status, {
    'content-type': 'application/json; charset=utf-8',
    'cache-control': 'no-store',
  });
  res.end(JSON.stringify(value));
}

function buildApiHandler(deps) {
  return async (req, res) => {
    try {
      if (req.method !== 'POST') {
        return sendJson(res, 405, { ok: false, error: 'method not allowed' });
      }
      const body = await readBody(req);
      const method = typeof body.method === 'string' ? body.method : '';

      const noWorkspace = (res) => sendJson(res, 200, { ok: false, code: 'no-workspace', error: 'unknown workspace' });
      const draftsWs = () => deps.resolveDraftsWorkspace(body);
      const draftsDirOf = (ws) => deps.resolveOutputDir(ws);
      const bookDirOf = async (ws, book) => {
        if (typeof book !== 'string' || book === '') return null;
        return safeChild(await draftsDirOf(ws), book);
      };

      switch (method) {
        /* ---- materials ---- */
        case 'list': {
          const entries = deps.listWorkspaces();
          const workspaces = [];
          for (const ws of entries) {
            workspaces.push({
              workspaceId: ws.workspaceId,
              name: ws.name,
              notesDir: ws.notesDir,
              draftsDir: ws.draftsDir,
              notes: await listNotes(ws.notesDir),
            });
          }
          return sendJson(res, 200, { ok: true, workspaces, noWorkspaces: workspaces.length === 0 });
        }
        case 'read': {
          const dir = deps.resolveNotesDir(body.workspaceId);
          if (dir === undefined) return noWorkspace(res);
          return sendJson(res, 200, await readNote(dir, body.name));
        }
        case 'search': {
          const entries = deps.listWorkspaces();
          const workspaces = [];
          for (const ws of entries) {
            workspaces.push({ workspaceId: ws.workspaceId, name: ws.name, notesDir: ws.notesDir, notes: await listNotes(ws.notesDir) });
          }
          const matches = await searchNotes(workspaces, body.q, MAX_SEARCH_MATCHES);
          return sendJson(res, 200, { ok: true, matches });
        }

        case 'import': {
          const dir = deps.resolveNotesDir(body.workspaceId);
          if (dir === undefined) return noWorkspace(res);
          return sendJson(res, 200, await importNote(dir, body.sourcePath));
        }
        case 'saveNote': {
          const dir = deps.resolveNotesDir(body.workspaceId);
          if (dir === undefined) return noWorkspace(res);
          return sendJson(res, 200, await saveNote(dir, body.name, body.content));
        }

        /* ---- books ---- */
        case 'openDir': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const base = await draftsDirOf(ws);
          const dir = (typeof body.book === 'string' && body.book !== '') ? safeChild(base, body.book) : base;
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          try { await mkdir(dir, { recursive: true }); } catch { /* ignore */ }
          return sendJson(res, 200, await openDir(dir));
        }
        case 'setOutputDir': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          return sendJson(res, 200, await deps.setOutputDir(ws, body.dir));
        }
        case 'listBooks': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await draftsDirOf(ws);
          return sendJson(res, 200, { ok: true, draftsDir: dir, books: await listBooks(dir) });
        }
        case 'createBook': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          return sendJson(res, 200, await createBook(await draftsDirOf(ws), body.name));
        }
        case 'renameBook': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          return sendJson(res, 200, await renameBook(await draftsDirOf(ws), body.oldName, body.newName));
        }

        /* ---- manuscript tree (卷 / 章) ---- */
        case 'tree': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, { ok: true, draftsDir: dir, volumes: await listVolumes(dir) });
        }
        case 'createVolume': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await createVolume(dir));
        }
        case 'createChapter': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await createChapter(dir, body.volume));
        }
        case 'readChapter': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await readChapter(dir, body.volume, body.chapter));
        }
        case 'writeChapter': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await writeChapter(dir, body.volume, body.chapter, body.content));
        }
        case 'renameVolume': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await renameVolume(dir, body.oldName, body.newName));
        }
        case 'renameChapter': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await renameChapter(dir, body.volume, body.oldName, body.newName));
        }
        case 'exportBook': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await exportBook(await draftsDirOf(ws), body.book));
        }
        case 'readOutline': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await readOutline(dir, body.book));
        }
        case 'writeOutline': {
          const ws = draftsWs();
          if (ws === undefined) return noWorkspace(res);
          const dir = await bookDirOf(ws, body.book);
          if (dir === null) return sendJson(res, 200, { ok: false, error: 'invalid book' });
          return sendJson(res, 200, await writeOutline(dir, body.book, body.content));
        }
        default:
          return sendJson(res, 200, { ok: false, error: `unknown method: ${method}` });
      }
    } catch (error) {
      sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
    }
  };
}

export function apply(ctx, config) {
  const web = ctx.get('webServer');
  if (web === undefined) return;

  const notesDirName = (config && config.notesDir) || DEFAULT_NOTES_DIR;
  const workspaces = () => ctx.get('workspaceRegistry');

  const getWorkspace = (workspaceId) => {
    if (typeof workspaceId !== 'string' || workspaceId === '') return undefined;
    return workspaces()?.get(workspaceId);
  };

  const workspaceIdForSession = (sessionId) => {
    if (typeof sessionId !== 'string' || sessionId === '') return undefined;
    const sessionStore = ctx.get('sessions');
    const cwd = sessionStore?.get(sessionId)?.header?.cwd;
    if (typeof cwd !== 'string' || cwd === '') return undefined;
    const registry = workspaces();
    if (registry === undefined) return undefined;
    const ws = (registry.list() ?? []).find((candidate) => {
      try {
        return path.normalize(candidate.path) === path.normalize(cwd);
      } catch {
        return false;
      }
    });
    return ws?.id;
  };

  const deps = {
    resolveNotesDir(workspaceId) {
      const ws = getWorkspace(workspaceId);
      if (ws === undefined) return undefined;
      return path.join(ws.path, notesDirName);
    },
    resolveOutputDir(ws) {
      return resolveOutputDir(ws);
    },
    setOutputDir(ws, dir) {
      return setOutputDir(ws, dir);
    },
    listWorkspaces() {
      const registry = workspaces();
      if (registry === undefined) return [];
      const out = [];
      for (const ws of registry.list() ?? []) {
        out.push({
          workspaceId: ws.id,
          name: ws.title ?? ws.id,
          notesDir: path.join(ws.path, notesDirName),
          draftsDir: path.join(ws.path, DEFAULT_DRAFTS_DIR),
        });
      }
      return out;
    },
    resolveDraftsWorkspace(body) {
      if (typeof body?.workspaceId === 'string' && body.workspaceId !== '') {
        const ws = getWorkspace(body.workspaceId);
        if (ws !== undefined) return ws;
      }
      const wsId = workspaceIdForSession(body?.sessionId);
      if (wsId !== undefined) {
        const ws = getWorkspace(wsId);
        if (ws !== undefined) return ws;
      }
      // Only fall back to the single workspace when it is unambiguous. With
      // multiple workspaces and no resolvable session cwd, refuse instead of
      // silently writing to the wrong workspace.
      const all = deps.listWorkspaces();
      if (all.length === 1) return getWorkspace(all[0].workspaceId);
      return undefined;
    },
  };

  const prefix = (config && config.route) || DEFAULT_ROUTE;
  const handler = buildApiHandler(deps);

  const iconPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'dsh-writing-desk.svg');
  const iconHandler = async (req, res) => {
    if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' });
    try {
      const data = await readFile(iconPath);
      res.writeHead(200, { 'content-type': 'image/svg+xml; charset=utf-8', 'cache-control': 'no-cache' });
      res.end(data);
    } catch {
      sendJson(res, 404, { ok: false, error: 'icon not found' });
    }
  };

  ctx.effect(() => web.register({ kind: 'prefix', path: prefix, handler }), 'writing-desk: api route');
  ctx.effect(() => web.register({ kind: 'exact', path: `${prefix}/icon.svg`, handler: iconHandler }), 'writing-desk: icon route');
}
