src / tools / constants.ts

import { existsSync, mkdirSync } from "fs";
import { join, normalize } from "path";
import { mkdir } from "fs/promises";

export const isWindows = process.platform === 'win32';

// ============================================================
// ✅ COGNITIVE CASTLE ROOT — from env or default
// ============================================================
// Priority:
//   1. COGNITIVE_CASTLE_ROOT (env)
//   2. BIDO_ROOT (env)
//   3. Default: D:\bido\2026 (Windows) or ./data/bido (other)
// ============================================================
export const cognitiveCastleRoot = normalize(
  process.env.COGNITIVE_CASTLE_ROOT ||
  process.env.BIDO_ROOT ||
  (isWindows && existsSync("D:\\")
    ? "D:\\bido\\2026"
    : "./data/bido")
);

export const targetBase = cognitiveCastleRoot;

console.info(`[Constants] 🏛️ Cognitive Castle Root: ${targetBase}`);

// ============================================================
// ✅ Memory directories (relative to root)
// ============================================================
export const MEMORY_BASE = join(targetBase, "memory");
export const SESSIONS_DIR = join(MEMORY_BASE, "sessions");
export const RAW_SESSIONS_DIR = join(MEMORY_BASE, "raw_sessions");
export const AWARENESS_FILE = join(MEMORY_BASE, "awareness", "awareness.json");

// ============================================================
// ✅ Ensure root exists
// ============================================================
if (!existsSync(targetBase)) {
  try {
    mkdirSync(targetBase, { recursive: true });
    console.info(`[Constants] ✅ Created root: ${targetBase}`);
  } catch (e: any) {
    console.error(`[Constants] ❌ Failed to create root: ${targetBase}`, e.message);
  }
}

// ============================================================
// ✅ Helpers
// ============================================================
export async function ensureDirectory(dirPath: string) {
  if (!existsSync(dirPath)) await mkdir(dirPath, { recursive: true });
}

export function resolveInsideBase(rel: string): string {
  if (rel.startsWith("raw_sessions/") || rel.startsWith("raw_sessions\\")) {
    return normalize(join(MEMORY_BASE, rel));
  }
  const isAbs = /^([A-Za-z]:)?[\\\/]/.test(rel);
  return normalize(isAbs ? rel : join(targetBase, rel));
}