/**
 * MCP server stderr tee — writes console.error output to both stderr
 * (for Claude Code) and a dated log file (for logs-read.sh retrieval).
 *
 * Claude Code spawns MCP servers as child processes and consumes their
 * stderr internally. The platform cannot intercept at the spawn level.
 * Each server must tee its own stderr to the account's log directory.
 */

import { mkdirSync, createWriteStream, type WriteStream } from "node:fs";
import { resolve } from "node:path";

/**
 * Patch process.stderr.write to tee output to a dated log file.
 *
 * Reads LOG_DIR from environment. When absent (dev mode, tool discovery),
 * does nothing — stderr continues to work as before.
 *
 * Log file: {LOG_DIR}/mcp-{serverName}-stderr-YYYY-MM-DD.log (append mode)
 */
export function initStderrTee(serverName: string): void {
  const logDir = process.env.LOG_DIR;
  if (!logDir) return; // Dev mode or tool discovery — stderr only

  let logStream: WriteStream;
  try {
    mkdirSync(logDir, { recursive: true });
    const date = new Date().toISOString().slice(0, 10);
    logStream = createWriteStream(
      resolve(logDir, `mcp-${serverName}-stderr-${date}.log`),
      { flags: "a" },
    );
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    process.stderr.write(
      `[${serverName}] WARNING: log file tee failed (${msg}), stderr only\n`,
    );
    return;
  }

  const originalWrite = process.stderr.write.bind(process.stderr);
  process.stderr.write = (
    chunk: string | Uint8Array,
    ...args: unknown[]
  ): boolean => {
    if (!logStream.destroyed) {
      logStream.write(chunk);
    }
    return (originalWrite as Function)(chunk, ...args);
  };
}
