import os from 'os';
import path from 'path';

import { readEnvFile } from './env.js';

// Read config values from .env (falls back to process.env).
// Secrets are NOT read here — they stay on disk and are loaded only
// where needed (jail-runner.ts) to avoid leaking to child processes.
const envConfig = readEnvFile([
  'ASSISTANT_NAME',
  'TELEGRAM_BOT_TOKEN',
  'AGENT_ENGINE',
  'PI_TUI_BIN',
  'PI_TUI_PROVIDER',
  'PI_TUI_MODEL',
]);

export const ASSISTANT_NAME =
  process.env.ASSISTANT_NAME || envConfig.ASSISTANT_NAME || 'Andy';
export const TELEGRAM_BOT_TOKEN =
  process.env.TELEGRAM_BOT_TOKEN || envConfig.TELEGRAM_BOT_TOKEN || '';
export const AGENT_ENGINE =
  process.env.AGENT_ENGINE || envConfig.AGENT_ENGINE || 'pi-tui';
export const PI_TUI_BIN = process.env.PI_TUI_BIN || envConfig.PI_TUI_BIN || 'pi';
export const PI_TUI_PROVIDER =
  process.env.PI_TUI_PROVIDER || envConfig.PI_TUI_PROVIDER || 'openrouter';
export const PI_TUI_MODEL =
  process.env.PI_TUI_MODEL ||
  envConfig.PI_TUI_MODEL ||
  'anthropic/claude-3.5-sonnet';
export const POLL_INTERVAL = 2000;
export const SCHEDULER_POLL_INTERVAL = 60000;

// Absolute paths needed for jail mounts
const PROJECT_ROOT = process.cwd();
const HOME_DIR = process.env.HOME || os.homedir();

// Mount security: allowlist stored OUTSIDE project root, never mounted into jails
export const MOUNT_ALLOWLIST_PATH = path.join(
  HOME_DIR,
  '.config',
  'clawdie-cp',
  'mount-allowlist.json',
);
export const STORE_DIR = path.resolve(PROJECT_ROOT, 'store');
export const GROUPS_DIR = path.resolve(PROJECT_ROOT, 'groups');
export const DATA_DIR = path.resolve(PROJECT_ROOT, 'data');
export const MAIN_GROUP_FOLDER = 'main';

export const JAIL_TIMEOUT = parseInt(
  process.env.JAIL_TIMEOUT || '1800000',
  10,
);
export const JAIL_MAX_OUTPUT_SIZE = parseInt(
  process.env.JAIL_MAX_OUTPUT_SIZE || '10485760',
  10,
); // 10MB default
export const IPC_POLL_INTERVAL = 1000;
export const IDLE_TIMEOUT = parseInt(process.env.IDLE_TIMEOUT || '1800000', 10); // 30min default — how long to keep jail alive after last result
export const MAX_CONCURRENT_JAILS = Math.max(
  1,
  parseInt(process.env.MAX_CONCURRENT_JAILS || '5', 10) || 5,
);

function escapeRegex(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

export const TRIGGER_PATTERN = new RegExp(
  `^@${escapeRegex(ASSISTANT_NAME)}\\b`,
  'i',
);

// Timezone for scheduled tasks (cron expressions, etc.)
// Uses system timezone by default
export const TIMEZONE =
  process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone;
