/**
 * Orchestrator configuration: paths, ports, and tokens.
 *
 * The orchestrator embeds pi as the agentic/model layer by spawning the `pi`
 * CLI in RPC mode (one subprocess per run) inside an isolated git worktree. All
 * kanban/documentation state still lives in this process's SQLite store; the
 * agent drives it by calling this server's own token-gated HTTP endpoints.
 */

import { execSync } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import path from 'node:path';

/** Resolve the git repository root from the current process cwd. */
function resolveRepoRoot(): string {
  try {
    return execSync('git rev-parse --show-toplevel', {
      encoding: 'utf8',
      stdio: ['ignore', 'pipe', 'ignore'],
    }).trim();
  } catch {
    return process.cwd();
  }
}

/** Absolute path to the monorepo root (used for git worktrees). */
export const REPO_ROOT = resolveRepoRoot();

/** Port this API server listens on (mirrors `index.ts`). */
export const PORT = Number(process.env.PORT ?? 3001);

/** Base URL the agent subprocess uses to reach this server over loopback. */
export const API_BASE = process.env.AGENT_API_BASE ?? `http://127.0.0.1:${PORT}`;

/** Directory holding agent worktrees (gitignored). */
export const WORKTREE_ROOT = path.join(REPO_ROOT, '.worktrees');

/** Branch prefix for agent-created branches. */
export const BRANCH_PREFIX = 'agent';

/** Path to the `pi` binary (override with PI_BIN for non-standard installs). */
export const PI_BIN = process.env.PI_BIN ?? 'pi';

/** Default tool allowlist handed to pi (explore + edit + run commands). */
export const PI_TOOLS = process.env.PI_TOOLS ?? 'read,bash,edit,write,ls,find,grep';

/**
 * Optional model override for orchestrator runs (e.g. `anthropic/claude-sonnet-4-5`).
 * When unset, pi uses the user's configured default model.
 */
export const PI_MODEL = process.env.PI_ORCHESTRATOR_MODEL ?? '';

/** Issue a fresh secret token authorising a single run's internal API calls. */
export function newToken(): string {
  return randomBytes(12).toString('hex');
}
