/* Paths, config and programs: the same ones the tools/ scripts use. */

import { AsyncLocalStorage } from "node:async_hooks";
import { spawn, which } from "../lib/runtime";
import { readFileSync, existsSync, copyFileSync, realpathSync, statSync } from "node:fs";
import { join, relative, resolve, sep } from "node:path";
import { homedir } from "node:os";
import { pickPython } from "../../../tools/lib/platform.mjs";
import { DEFAULT_CHANNEL, channelEnv, channelRoot as channelRootOf } from "../../../tools/lib/paths.mjs";
import { CHANNEL_CONFIG_FILE, readConfig } from "../../../tools/lib/config.mjs";

/* Two roots, as in tools/lib/paths.mjs. CODE_ROOT holds tools/, templates/, docs/ and the .venv: the
   project dir (studio/api/services → ../../..), or OMNI_CODE_ROOT when this code runs bundled into the
   compiled `omni` binary, whose own path is /$bunfs/…. ROOT is the workspace (videos/, the config, .env,
   the dot folders): OMNI_HOME, else OMNIVIDEO_ROOT (tests use a tmp fixture root with its own
   omnivideo.config.json and videos/), else the code root. */
export const CODE_ROOT = resolve(process.env.OMNI_CODE_ROOT || resolve(import.meta.dirname, "..", "..", ".."));
export const ROOT = resolve(process.env.OMNI_HOME || process.env.OMNIVIDEO_ROOT || CODE_ROOT);
/* The Claude dir of the sessions from before the agent accounts (tools/lib/agents.mjs, where
   ~/.claude is refused): an old turn without `account` ran here. */
export const CLAUDE_PERSONAL_DIR = join(homedir(), ".claude-personal");
export const TOOLS_DIR = join(CODE_ROOT, "tools");
export const QUEUE_DIR = join(ROOT, ".queue");
/* fresh clone (or workspace) opened before `node tools/setup.mjs`: the config comes from the example */
if (!existsSync(join(ROOT, "omnivideo.config.json")) && existsSync(join(CODE_ROOT, "omnivideo.config.example.json")))
  copyFileSync(join(CODE_ROOT, "omnivideo.config.example.json"), join(ROOT, "omnivideo.config.json"));
/* the workspace's config as it was when the studio started: only for what belongs to the machine and is read once
   (the Python, the node, the Claude binary). Anything a request reads is channelConfig(), which follows the channel. */
export const BOOT_CONFIG = JSON.parse(readFileSync(join(ROOT, "omnivideo.config.json"), "utf8"));

/* --- the channel of a request (docs/specs/multi-channel.md, ADR 0028) ---------------------------------------------
   The studio serves every channel of the workspace. The middleware (api/middleware/channel.ts) runs each request inside
   withChannel(<the request's channel>), and everything below reads it: channelRoot() is the folder of the channel's
   videos/, brand/, channel/, user-skills/ and dot folders; ROOT stays the workspace (the queue, the sessions, the agent
   accounts, kit/). Work that is not a request (watchers, alarms, a turn that ends) names its channel explicitly. */
const channelStore = new AsyncLocalStorage<string>();
/** the channel the code runs for: the request's, else the default one */
export const channelId = (): string => channelStore.getStore() ?? DEFAULT_CHANNEL;
/** runs `fn` for channel `id` (what the middleware does for a request) */
export const withChannel = <T>(id: string | undefined | null, fn: () => T): T =>
  channelStore.run(id || DEFAULT_CHANNEL, fn);
/** the folder of channel `id` (the current one by default): the workspace itself for the default channel */
export const channelRoot = (id: string = channelId()): string => channelRootOf(ROOT, id);
/** a video's folder as an agent session names it: relative to the workspace, the session's cwd (videos/<slug> for the
 *  default channel, channels/<id>/videos/<slug> for another) */
export const videoPath = (slug: string, id: string = channelId()): string =>
  relative(ROOT, join(channelRoot(id), "videos", slug));
/** the channel a path of the workspace belongs to: channels/<id>/… is that channel's, anything else the default one's
 *  (what background work uses when it only has a video's folder) */
export function channelOfPath(p: string): string {
  /* the video folders are kept with links resolved (on macOS /tmp is /private/tmp): either form of the workspace counts */
  for (const base of [ROOT, ROOT_REAL]) {
    const m = /^channels\/([a-z0-9][a-z0-9-]*)(\/|$)/.exec(relative(base, p).split(sep).join("/"));
    if (m) return m[1];
  }
  return DEFAULT_CHANNEL;
}
const ROOT_REAL = (() => {
  try {
    return realpathSync(ROOT);
  } catch {
    return ROOT;
  }
})();
/** the environment of a child that works on channel `id` (OMNI_CHANNEL, or nothing for the default one) */
export const channelEnvOf = (id: string = channelId(), base: Record<string, string | undefined> = process.env) =>
  channelEnv(id, base) as Record<string, string>;

/* the config of a channel (the workspace's with the channel's own part over it, tools/lib/config.mjs), reread when either
   file changes */
const configCache = new Map<string, { stamp: string; cfg: any }>();
const mtimeOf = (file: string) => {
  try {
    return statSync(file).mtimeMs;
  } catch {
    return 0;
  }
};
/** the config a request of channel `id` sees (the current channel by default) */
export function channelConfig(id: string = channelId()): any {
  const root = channelRoot(id);
  const own = root === ROOT ? 0 : mtimeOf(join(root, CHANNEL_CONFIG_FILE));
  const stamp = `${mtimeOf(join(ROOT, "omnivideo.config.json"))}:${own}`;
  const hit = configCache.get(root);
  if (hit && hit.stamp === stamp) return hit.cfg;
  const cfg = readConfig(root) ?? BOOT_CONFIG;
  configCache.set(root, { stamp, cfg });
  return cfg;
}

/* the project's Python (.venv, created by `node tools/setup.mjs`); without it, the one in the config
   (the VoiceStudio venv) and, last, the system python3 */
export const PYTHON: string = pickPython(CODE_ROOT, [BOOT_CONFIG.voicestudio?.python ?? ""]);
/* config path: relative paths are resolved from the workspace */
export const resolvePath = (p: string) => resolve(ROOT, p.replace(/^~(?=\/|$)/, homedir()));
/* the node on PATH is the same one the chat uses; without PATH (studio opened outside a
   shell), the one in the config */
export const NODE: string = which("node") ?? BOOT_CONFIG.premiere?.node ?? "node";

export type RunResult = { stdout: string; stderr: string; code: number };

/* a tool works on the request's channel: OMNI_CHANNEL goes along (tools/lib/paths.mjs); its cwd stays the workspace */
export async function run(command: string[], env: Record<string, string> = {}): Promise<RunResult> {
  const p = spawn(command, { cwd: ROOT, stdout: "pipe", stderr: "pipe", env: { ...channelEnvOf(), ...env } });
  const [stdout, stderr, code] = await Promise.all([
    new Response(p.stdout).text(),
    new Response(p.stderr).text(),
    p.exited,
  ]);
  return { stdout, stderr, code };
}

export function readJson<T = any>(file: string): T | null {
  try {
    return JSON.parse(readFileSync(file, "utf8"));
  } catch {
    return null;
  }
}

export function readText(file: string): string | null {
  try {
    return readFileSync(file, "utf8");
  } catch {
    return null;
  }
}
